package sisi.invoices;

import java.io.File;
import java.io.FileNotFoundException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;

import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.Sessions;
import org.zkoss.zk.ui.event.CreateEvent;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zk.ui.event.ForwardEvent;
import org.zkoss.zk.ui.sys.ComponentsCtrl;
import org.zkoss.zk.ui.util.ConventionWires;
import org.zkoss.zul.Bandbox;
import org.zkoss.zul.Button;
import org.zkoss.zul.Checkbox;
import org.zkoss.zul.Combobox;
import org.zkoss.zul.Comboitem;
import org.zkoss.zul.ComboitemRenderer;
import org.zkoss.zul.Datebox;
import org.zkoss.zul.Doublebox;
import org.zkoss.zul.Filedownload;
import org.zkoss.zul.Groupbox;
import org.zkoss.zul.Hbox;
import org.zkoss.zul.Intbox;
import org.zkoss.zul.Label;
import org.zkoss.zul.ListModelList;
import org.zkoss.zul.Listbox;
import org.zkoss.zul.Listcell;
import org.zkoss.zul.Listfooter;
import org.zkoss.zul.Listheader;
import org.zkoss.zul.Listitem;
import org.zkoss.zul.ListitemRenderer;
import org.zkoss.zul.Messagebox;
import org.zkoss.zul.Textbox;
import org.zkoss.zul.Window;

import sisi.General;
import sisi.bank.Bank;
import sisi.bank.BankController;
import sisi.currency.Currency;
import sisi.enquires.Reqquote;
import sisi.enquires.Reqshipfuelass;
import sisi.enquires.ReqshipfuelassController;
import sisi.enquires.Reqshipfuelassdetail;
import sisi.enquires.ReqshipfuelassdetailController;
import sisi.payment.Payment;
import sisi.payment.PaymentsController;
import sisi.ports.Port;
import sisi.ports.PortController;
import sisi.products.Product;
import sisi.products.ProductsController;
import sisi.unitmeasure.Unitmeasure;
import sisi.unitmeasure.UnitmeasureController;
import sisi.vatarticles.Vatarticle;
import sisi.vatarticles.VatarticleController;
import sisi.yacht.Anayacht;
import sisi.yacht.AnayachtController;


/**
 * InvoicesWindow.java - Controller class for <i>Invoices window</i>. 
 * @author Pedro Gonzalez pedro@sisisoftware.it
 * @author Claudio Pelosi claudio@sisisoftware.it
 * @author SISI Software S.n.c. - www.sisisoftware.it
 * @version 1.0, 09/10/2014
 * 
 */


@SuppressWarnings({ "rawtypes", "unchecked", "serial" })
public class InvoicesWindow extends Window implements 
				org.zkoss.zk.ui.ext.AfterCompose {

private Listbox boxEnqNumber;

protected Map<String, Object> args;
private Textbox tbArt15;
private Textbox tbBoatName, tbBoatContact, tbPortToRefuel, tbCountry;
private Datebox dbDeliveryDate;
private Bandbox bbEnqNumber;
private Intbox idBoatName, idEnqNumber;

private Textbox tbSupplier, tbCorporation;
private Listbox boxCurrency;
private Bandbox bbCurrency;
private Textbox tbCustomerNote;

private Window windowInvoices;
private Integer valoreOpzioneMenu = 0, invoiceQuante = 0, invoiceAttuale = 1;
private Intbox ibNumRecords, ibSuppId;
private Bandbox bbCurRecNum;
private Listbox boxAllRecords;

private Label lblSuppId;
private Textbox tbRecnum, tbDt_UP, tbCustId, tbCustName, tbOrder, tbCustNumInvoice, tbInitial, tbFullnvoiceRef;
private Textbox tbSuppNumInvoice;

private Label lblTotalTaxable, lblDeliveryDT, lblXChRate, lblTotalVAT, lblCurr, lblTotalInvoice, lblInvoiceDt;
private Label lblCreditTerms, lblStat, lblDueDate, lblType, lblInvCeDtReg, lblPiva, lblCF, lblMemento, lblDateFormat;
private Label lblCustNumInvoice, lblSuppNumInvoice;
private Doublebox dbTotalTaxable, dbTotalVAT, dbXChRate, dbTotalInvoice;
private Datebox dbDeliveryDt, dbInvoiceDt, dbDueDate, dbInvCeDtReg;
private Bandbox bbCreditTerms;
private Listbox boxCreditTerms;
private Textbox tbStat, tbType, tbInvCeDtReg, tbPiva, tbCF, tbMemento;
private Hbox hbPivaCF;
private Checkbox cbFuel, cbImmediateInvoice;
private Button btnNoteCustomer, btnGetInvoiceNumber, btnPrintInvoice, btnCreditNoteDebitNote, btnCash;

private Listbox boxInvoiceDetail;

private Button btnLockedForms, btnCongruence, btnCloseInvoice, btnMarkTheWholeInvoice;

private Window windowEditCustomerNoteInvoiceHeader;
private List listaInvoices;
private Intbox ibRecNum, ibSeq;
private Label lblSeq, lblBank;
private Listfooter lfTaxable, lfVAT, lfTotVAT;
private Combobox cbBank, cbDateFormat;
private boolean lockedForms = true;
private Listheader lhN, lfN;
private Groupbox gbOtherButtons;


		public void onCreate$windowInvoices(Event event) {
		
			CreateEvent ce = (CreateEvent) ((ForwardEvent) event).getOrigin();
			args = (Map<String, Object>) ce.getArg();
			
			valoreOpzioneMenu = (Integer)args.get("valore");
			
			ListModelList listModelListEnqNumber = new ListModelList();
			
			if (valoreOpzioneMenu==1){
				listModelListEnqNumber.addAll(new ReqshipfuelassController().getListaEnqNumberCC_SC_HI_CL_IV());
				btnCreditNoteDebitNote.setLabel("Credit Note");
			} else if (valoreOpzioneMenu==5) {
				listModelListEnqNumber.addAll(new ReqshipfuelassController().getListaEnqNumberCC_SC_HI_CL_IV_Supplier());
				btnCreditNoteDebitNote.setLabel("Debit Note");
			}
			
			//Component tmp = windowInvoices.getFellow("boxEnqNumber");
			//boxEnqNumber = (Listbox) tmp; 
			
			boxEnqNumber.setModel(listModelListEnqNumber); 
			boxEnqNumber.setItemRenderer(new EnqNumberRenderer());
			bbEnqNumber.setReadonly(false);
	
			idEnqNumber.setValue(null);
				
			lblSuppId.setVisible(false);
			ibSuppId.setVisible(false);
			tbSupplier.setVisible(false);
			cbFuel.setVisible(false);
			hbPivaCF.setVisible(false);
			btnGetInvoiceNumber.setVisible(false);
			lblBank.setVisible(false);
			cbBank.setVisible(false);
			btnPrintInvoice.setVisible(false);
			

			
			if (valoreOpzioneMenu==1){
				windowInvoices.setTitle("Customer Billing");
				cbFuel.setVisible(true);
				hbPivaCF.setVisible(true);
				btnGetInvoiceNumber.setVisible(true);
				lblBank.setVisible(true);
				cbBank.setVisible(true);
				btnPrintInvoice.setVisible(true);
				lblSuppNumInvoice.setVisible(false);
				tbSuppNumInvoice.setVisible(false);
				lblDateFormat.setVisible(true);
				cbDateFormat.setVisible(true);
				cbImmediateInvoice.setVisible(true);
			} else if (valoreOpzioneMenu==2){
				windowInvoices.setTitle("Customer Billing Edit & Manual");
				cbFuel.setVisible(true);
				hbPivaCF.setVisible(true);
				btnGetInvoiceNumber.setVisible(true);
				lblBank.setVisible(true);
				cbBank.setVisible(true);
				btnPrintInvoice.setVisible(true);
				lblSuppNumInvoice.setVisible(false);
				tbSuppNumInvoice.setVisible(false);
			} else if (valoreOpzioneMenu==5){
				windowInvoices.setTitle("Supplier's Billing");
				lblSuppId.setVisible(true);
				ibSuppId.setVisible(true);
				tbSupplier.setVisible(true);
				gbOtherButtons.setVisible(false);
				lblSuppNumInvoice.setVisible(true);
				tbSuppNumInvoice.setVisible(true);
				tbCustNumInvoice.setVisible(false);
				lblCustNumInvoice.setVisible(false);
				lblMemento.setVisible(true);
				tbMemento.setVisible(true);
				btnNoteCustomer.setVisible(false);

			} else if (valoreOpzioneMenu==6){
				windowInvoices.setTitle("Supplier's Billing Edit & Manual"); 
			}

			
			List<Bank> listBank = new BankController().getBankList(null);
			ListModelList listModelListSupplier = new ListModelList();
			listModelListSupplier.addAll(listBank);
			cbBank.setModel(listModelListSupplier);
			cbBank.setItemRenderer(new BankItemRenderer());

			
			if (bbEnqNumber.getValue()==null || bbEnqNumber.getValue().isEmpty() || tbStat.getValue()==null || !tbStat.getValue().equalsIgnoreCase("HI") ){
				lockedForms = true;
			}
			controlLockedFields();
			
			if (valoreOpzioneMenu==1){
				Custinvoice ciTmp = (Custinvoice)args.get("ci");
				if (ciTmp!=null){
					bbEnqNumber.setValue(""+ciTmp.getOrder());
					changeORokEnqNumber(null);
				}
			} else if (valoreOpzioneMenu==5){
				Suppinvoice siTmp = (Suppinvoice)args.get("si");
				if (siTmp!=null){
					bbEnqNumber.setValue(""+siTmp.getOrder());
					changeORokEnqNumber(null);
				}
				
			}
			
		}

		
	public void afterCompose() {

		// wire variables
		ConventionWires.wireVariables(this, this);

		// auto forward
		ConventionWires.addForwards(this, this);
	}

	
	public void onSelect$boxEnqNumber(Event event){
		int iSelected = boxEnqNumber.getSelectedIndex();
		if (iSelected == -1){
			return;
		}
		resetFields();
		Object oEnqNumber = boxEnqNumber.getItemAtIndex(iSelected).getAttribute("rigaEnqNumber");
		Object[] oRiga = (Object[])oEnqNumber;
		Integer id = (Integer)oRiga[0];
		idEnqNumber.setValue(id);
		invoiceAttuale = 1;
		if (valoreOpzioneMenu==5){
			ibSuppId.setValue((Integer)oRiga[8]);
		}

		changeORokEnqNumber(null);

	}
	
	
	public void onOK$bbEnqNumber(Event event){
		ibSuppId.setValue(0);
		changeORokEnqNumber(event);
	}
	
	public void onChange$bbEnqNumber(Event event){
		ibSuppId.setValue(0);
		changeORokEnqNumber(event); 
	}
	
	private void changeORokEnqNumber(Event event){
		
		lockedForms = true;
		controlLockedFields();
		
		if (bbEnqNumber.getValue()==null){
			return;
		}
		invoiceAttuale = 1;

		List lista = new ArrayList();
		if (valoreOpzioneMenu==1){
			lista = new ReqshipfuelassController().getListaEnqNumberCC_SC_HI_CL_IV();
		} else if ( valoreOpzioneMenu==5){
			lista = new ReqshipfuelassController().getListaEnqNumberCC_SC_HI_CL_IV_Supplier();
		}

		
		boolean valido = false;
		int zz=1;
		for (Object object : lista) {
			Object[] oRiga = (Object[])object;
			Integer id = (Integer)oRiga[0];
			if ( Integer.valueOf( bbEnqNumber.getValue() ).compareTo(id)==0){
				idEnqNumber.setValue(id);
				valido = true;
				if (valoreOpzioneMenu==5){
					valido = false;
					if (ibSuppId.getValue()!=null && ibSuppId.getValue()==0){
						ibSuppId.setValue((Integer)oRiga[8]);
						valido = true;
						invoiceAttuale = zz;
					} else if (ibSuppId.getValue().equals( (Integer)oRiga[8] )) {
						valido = true;
						invoiceAttuale = zz;
					}
					zz++;
				}
				
				if (valido = true){
					break;
				}
			}
		}
		
		// seconda validazione
		if ( valoreOpzioneMenu==1 && new CustinvoiceController().getCountEqualsEnqNumber(Integer.valueOf( bbEnqNumber.getValue() ))==0 ){
			new General().errorBox("Confirmation to customer has to be done!", "Information");
			resetFields();
			return;
		} else if (valoreOpzioneMenu==5 && new SuppinvoiceController().getCountEqualsEnqNumber(Integer.valueOf( bbEnqNumber.getValue() ))==0 ){
			new General().errorBox("Confirmation to supplier has to be done!", "Information");
			resetFields();
			return;
		}
		

		if (!valido){
			Messagebox.show("Enquire number not valid! - "+bbEnqNumber.getValue(), "Information", Messagebox.OK, Messagebox.INFORMATION);
			resetFields();
		} else {
			idEnqNumber.setValue(Integer.valueOf( bbEnqNumber.getValue() ));
			viewIntestazioni(Integer.valueOf( bbEnqNumber.getValue() ));
		}
	}
		
	private void resetFields(){
		tbCountry.setValue("");
		tbBoatName.setValue("");
		tbBoatContact.setValue("");
		dbDeliveryDate.setValue(null);
		dbDeliveryDate.setButtonVisible(false);
		tbPortToRefuel.setValue("");			
		tbCountry.setValue("");
		tbArt15.setValue( "NO" );
		
		ibNumRecords.setValue(null);
		bbCurRecNum.setValue("");
		
	
		ListModelList listModelList = new ListModelList();
		boxAllRecords.setModel(listModelList);
		if (valoreOpzioneMenu==1){
			boxAllRecords.setItemRenderer(new AllCustInvoices() );
		} else if (valoreOpzioneMenu==5){
			boxAllRecords.setItemRenderer(new AllSuppInvoices() );
		}
		
		tbRecnum.setValue("");
		tbDt_UP.setValue( "" );
		tbCustId.setValue("");
		tbCustName.setValue("");
		tbOrder.setValue("");
		tbCustNumInvoice.setValue("");
		tbSuppNumInvoice.setValue("");
		tbInitial.setValue("");
		tbFullnvoiceRef.setValue("");
		ibSuppId.setValue(0);
		tbSupplier.setValue("");
		
		
		dbTotalTaxable.setValue(0);
		dbTotalVAT.setValue(0);
		dbTotalInvoice.setValue(0);
		bbCreditTerms.setValue("");
		listModelList = new ListModelList();
		boxCreditTerms.setModel(listModelList);
		boxCreditTerms.setItemRenderer(new PaymentsRenderer());
		bbCreditTerms.setReadonly(true);
		
		dbInvoiceDt.setValue(null);
		dbDueDate.setValue(null);
		dbInvCeDtReg.setValue(null);
		tbPiva.setValue("");
		dbDeliveryDt.setValue(null);
		
		// listbox currency	
		ListModelList listModelList2 = new ListModelList();
		boxCurrency.setModel(listModelList2);
		boxCurrency.setItemRenderer(new CurrencyRenderer());
		
		bbCurrency.setValue("");
		bbCurrency.setReadonly(true);

		tbStat.setValue("");
		tbType.setValue("");
		tbCF.setValue("");
		
		dbXChRate.setValue(1.00);
		
		cbFuel.setChecked(false);
		tbMemento.setValue("");	

		ListModelList listModelListEnqNumber = new ListModelList();
		boxInvoiceDetail.setModel(listModelListEnqNumber); 
		
		if (valoreOpzioneMenu==1){
			boxInvoiceDetail.setItemRenderer(new CustInvoiceRenderer());		
		} else if (valoreOpzioneMenu==5){
			boxInvoiceDetail.setItemRenderer(new SuppInvoiceRenderer());
			lhN.setVisible(false);
		}

		
	}
	
	private void viewIntestazioni(Integer idEnqNumber){
		Reqshipfuelass reqshipfuelass = new ReqshipfuelassController().getxId(idEnqNumber);
		
		tbBoatName.setValue(reqshipfuelass.getVesselname());		
		tbBoatContact.setValue(reqshipfuelass.getCaptain());
		dbDeliveryDate.setValue(reqshipfuelass.getDeliverydt());
		dbDeliveryDate.setButtonVisible(false);
		tbPortToRefuel.setValue(reqshipfuelass.getPorttoref());
		
		if (reqshipfuelass.getIdportref()!=null && reqshipfuelass.getIdportref()!=0){
			Port porto = new PortController().getPortxId(reqshipfuelass.getIdportref());
			tbCountry.setValue(porto.getCountry());
		}

		Anayacht yacht = new AnayachtController().getAnayachtxId(reqshipfuelass.getVesselnameid());
		if (yacht!=null){
			tbCorporation.setValue(yacht.getCorporation());
			idBoatName.setValue(yacht.getId());
		} else {
			tbCorporation.setValue("");
			idBoatName.setValue(0);
		}
		
		tbArt15.setValue( (reqshipfuelass.getArt15()==null||!reqshipfuelass.getArt15()?"NO":"SI") );
		viewInvoiceHeader(null);
	}


	private void viewInvoiceHeader(Integer invoiceAttuale_){
		
		if ( bbEnqNumber.getValue()==null || bbEnqNumber.getValue().isEmpty() ){
			return;
		}
		
		if (valoreOpzioneMenu==1){
			invoiceQuante = new CustinvoiceController().getCountEqualsEnqNumber(Integer.valueOf( bbEnqNumber.getValue() ));
		} else if (valoreOpzioneMenu==5){
			invoiceQuante = new SuppinvoiceController().getCountEqualsEnqNumber(Integer.valueOf( bbEnqNumber.getValue() ));
		}
		if (invoiceAttuale_!=null){
			invoiceAttuale = invoiceAttuale_;
		}
		ibNumRecords.setValue(invoiceQuante);
		bbCurRecNum.setValue(""+invoiceAttuale);
		
		
		ListModelList listModelList = new ListModelList();
		List listaInvoices = new ArrayList(); 
		if (valoreOpzioneMenu==1){
			listaInvoices = new CustinvoiceController().getList(Integer.valueOf( bbEnqNumber.getValue() ), Integer.valueOf( idBoatName.getValue() ) );
		} else if (valoreOpzioneMenu==5){
			//listaInvoices = new SuppinvoiceController().getList(Integer.valueOf( bbEnqNumber.getValue() ), ibSuppId.getValue() );
			listaInvoices = new SuppinvoiceController().getList(Integer.valueOf( bbEnqNumber.getValue() ) );
		}
		listModelList.addAll(listaInvoices); 
		boxAllRecords.setModel(listModelList);
		if (valoreOpzioneMenu==1){
			boxAllRecords.setItemRenderer(new AllCustInvoices() );
		} else if (valoreOpzioneMenu==5){
			boxAllRecords.setItemRenderer(new AllSuppInvoices() );
		}
		
		if (listaInvoices!=null && listaInvoices.size()>0){
			bbCurRecNum.setValue(""+invoiceAttuale);
			boxAllRecords.setSelectedIndex((invoiceAttuale-1));
			
			if (valoreOpzioneMenu==1){
				Custinvoice ciTmp = (Custinvoice)args.get("ci");
				if (ciTmp!=null){
					for (int i = 0; i < listaInvoices.size(); i++) {
						Custinvoice ciTmp2 = (Custinvoice)listaInvoices.get(i);
						if (ciTmp2.getCustnuminvoice().compareTo(ciTmp.getCustnuminvoice())==0){
							invoiceAttuale = i+1;
							bbCurRecNum.setValue(""+invoiceAttuale);
							boxAllRecords.setSelectedIndex((invoiceAttuale-1));
							break;
						}
					}
				}
			} else if (valoreOpzioneMenu==5){
				Suppinvoice siTmp = (Suppinvoice)args.get("si");
				if (siTmp!=null){
					for (int i = 0; i < listaInvoices.size(); i++) {
						Suppinvoice siTmp2 = (Suppinvoice)listaInvoices.get(i);
						if (siTmp2.getSuppnuminvoice().compareTo(siTmp.getSuppnuminvoice())==0){
							invoiceAttuale = i+1;
							bbCurRecNum.setValue(""+invoiceAttuale);
							boxAllRecords.setSelectedIndex((invoiceAttuale-1));
							break;
						}
					}
				}				
			}
			
		}
		
		viewInvoiceHeader2();
		
	}
	
	public void onSelect$boxAllRecords(Event event){
		int iSelected = boxAllRecords.getSelectedIndex();
		if (iSelected == -1){
			return;
		}
		invoiceAttuale = iSelected + 1;
		viewInvoiceHeader2();
	}

	
	public void onChange$bbCurRecNum(){
		//invoiceAttuale = Integer.valueOf( bbCurRecNum.getValue() ) ;
		viewInvoiceHeader2();
	}
	
	private void viewInvoiceHeader2(){
		
		listaInvoices = new ArrayList();
		if (valoreOpzioneMenu==1){
			listaInvoices = new CustinvoiceController().getList(Integer.valueOf( bbEnqNumber.getValue() ), Integer.valueOf( idBoatName.getValue() ) );	
		} else if (valoreOpzioneMenu==5){
			listaInvoices = new SuppinvoiceController().getList(Integer.valueOf( bbEnqNumber.getValue() ) );
		}
		 
		if ((invoiceAttuale)<=0 || listaInvoices.size()<invoiceAttuale){
			return;
		}
		
		
		// listbox currency	
		ListModelList listModelList2 = new ListModelList();
		List<Currency> listaCurrency = new sisi.currency.CurrencyController().getList(null);
		listModelList2.addAll(listaCurrency);
		boxCurrency.setModel(listModelList2);
		boxCurrency.setItemRenderer(new CurrencyRenderer());
		
		// credit terms
		ListModelList listModelList = new ListModelList();
		List<Payment> listPayments = new PaymentsController().getPaymentList(null);
		listModelList.addAll(listPayments);
		boxCreditTerms.setModel(listModelList);
		boxCreditTerms.setItemRenderer(new PaymentsRenderer());
		bbCreditTerms.setReadonly(true);
		
		if (valoreOpzioneMenu==1){
			
			Custinvoice ci = (Custinvoice)listaInvoices.get((invoiceAttuale-1));
			
			tbRecnum.setValue(""+ci.getRecnum());
			tbDt_UP.setValue( General.formatoFechaOra( ci.getDtUp() ) );
			tbCustId.setValue(""+ci.getCustid());
			tbCustName.setValue(ci.getCustname());
			tbOrder.setValue(""+ci.getOrder());
			tbCustNumInvoice.setValue(""+ci.getCustnuminvoice());
			tbInitial.setValue(ci.getInitial());
			String fullInvoiceRef = ""+( ci.getCustnuminvoice()!=null?ci.getCustnuminvoice():"")+"/"+(ci.getInitial()!=null?ci.getInitial():"")+"/"+(ci.getInvoicedt()!=null?ci.getInvoicedt().getYear():"");
			tbFullnvoiceRef.setValue(fullInvoiceRef);
			
			
			
			dbTotalTaxable.setValue(ci.getTotaltaxedvat());
			dbTotalVAT.setValue(ci.getTotalvat());
			dbTotalInvoice.setValue(ci.getTotalinvoice());
			
			
			bbCreditTerms.setValue(ci.getCreditterms());
			
			if (bbCreditTerms.getValue()!=null && !bbCreditTerms.getValue().isEmpty()){
				for (int i = 0; i < listPayments.size(); i++) {
					Payment payment = (Payment)listPayments.get(i);
					if (payment.getTerms().equalsIgnoreCase(bbCreditTerms.getValue())){
						boxCreditTerms.setSelectedIndex(i);
						break;
					}
				}
			}
	
			
			dbInvoiceDt.setValue(ci.getInvoicedt());
			dbDueDate.setValue(ci.getDuedate());
			dbInvCeDtReg.setValue(ci.getInvoicedtreg());
			tbPiva.setValue(ci.getPIva());
			
			dbDeliveryDt.setValue(ci.getDeliverydt());
			
			
			bbCurrency.setValue("");
			bbCurrency.setReadonly(true);
			if (ci.getCurr()!=null && !ci.getCurr().isEmpty()){
				bbCurrency.setValue(ci.getCurr());
				for (int i = 0; i < listaCurrency.size(); i++) {
					Currency cu = (Currency)listaCurrency.get(i);
					if (cu.getCurr().equalsIgnoreCase(ci.getCurr())){
						boxCurrency.setSelectedIndex(i);
						break;
					}
				}
			}
	
			tbStat.setValue(ci.getStat());
			tbType.setValue(ci.getType());
			tbCF.setValue(ci.getCfId());
			
			dbXChRate.setValue( (ci.getExchangerate()==0 ) ? 1.00 :  ci.getExchangerate() );
			
			cbFuel.setChecked( (ci.getFuel()==null ? false : ci.getFuel() ) );
			tbMemento.setValue(ci.getMemento());
			
		} else if (valoreOpzioneMenu==5){
			Suppinvoice si = (Suppinvoice)listaInvoices.get((invoiceAttuale-1));
			
			tbRecnum.setValue(""+si.getRecnum());
			tbDt_UP.setValue( General.formatoFechaOra( si.getDtUp() ) );
			tbCustId.setValue(""+si.getCustid());
			tbCustName.setValue(si.getCustname());
			tbOrder.setValue(""+si.getOrder());
			tbSuppNumInvoice.setValue(""+si.getSuppnuminvoice());
			tbInitial.setValue(si.getInitial());
			String fullInvoiceRef = ""+( si.getSuppnuminvoice()!=null?si.getSuppnuminvoice():"")+"/"+(si.getInitial()!=null?si.getInitial():"")+"/"+(si.getInvoicedt()!=null?si.getInvoicedt().getYear():"");
			tbFullnvoiceRef.setValue(fullInvoiceRef);
			
			dbTotalTaxable.setValue(si.getTottaxed()); 
			dbTotalVAT.setValue(si.getTotvat());
			dbTotalInvoice.setValue(si.getTotalinvoice());
			
			
			bbCreditTerms.setValue(si.getCreditterms());
			
			if (bbCreditTerms.getValue()!=null && !bbCreditTerms.getValue().isEmpty()){
				for (int i = 0; i < listPayments.size(); i++) {
					Payment payment = (Payment)listPayments.get(i);
					if (payment.getTerms().equalsIgnoreCase(bbCreditTerms.getValue())){
						boxCreditTerms.setSelectedIndex(i);
						break;
					}
				}
			}

			
			dbInvoiceDt.setValue(si.getInvoicedt());
			dbDueDate.setValue(si.getDuedate());
			dbInvCeDtReg.setValue(si.getInvoicedtreg());			
			dbDeliveryDt.setValue(si.getDeliverydt());
			
			
			bbCurrency.setValue("");
			bbCurrency.setReadonly(true);
			if (si.getCurr()!=null && !si.getCurr().isEmpty()){
				bbCurrency.setValue(si.getCurr());
				for (int i = 0; i < listaCurrency.size(); i++) {
					Currency cu = (Currency)listaCurrency.get(i);
					if (cu.getCurr().equalsIgnoreCase(si.getCurr())){
						boxCurrency.setSelectedIndex(i);
						break;
					}
				}
			}
	
			tbStat.setValue(si.getStat());
			tbType.setValue(si.getType());
			
			dbXChRate.setValue( si.getExchangerate()==0 ? 1 : si.getExchangerate());
			tbMemento.setValue(si.getMemento());
			
			ibSuppId.setValue( si.getSuppid() );
			tbSupplier.setValue( si.getSuppname() );
			
		}
		
		
		viewInvoiceDetail();
		
	}
	
	private void viewInvoiceDetail(){
		Integer orderNum = Integer.valueOf(tbOrder.getValue());
		Integer recNum = Integer.valueOf(tbRecnum.getValue());
		
		if (orderNum==null || recNum == null){
			return;
		}

		if (valoreOpzioneMenu==1 || valoreOpzioneMenu==2 || valoreOpzioneMenu==4){
			List<Custinvoicedetail> listInvoiceDetail = new CustinvoicedetailController().getList(orderNum, recNum );		
			ListModelList listModelListEnqNumber = new ListModelList();
			listModelListEnqNumber.addAll(listInvoiceDetail);
			boxInvoiceDetail.setModel(listModelListEnqNumber); 
			boxInvoiceDetail.setItemRenderer(new CustInvoiceRenderer());
		} else if (valoreOpzioneMenu==5 || valoreOpzioneMenu==6 || valoreOpzioneMenu==8){
			List<Suppinvoicedetail> listInvoiceDetail = new SuppinvoicedetailController().getList(orderNum, recNum );		
			ListModelList listModelListEnqNumber = new ListModelList();
			listModelListEnqNumber.addAll(listInvoiceDetail);
			boxInvoiceDetail.setModel(listModelListEnqNumber); 
			boxInvoiceDetail.setItemRenderer(new SuppInvoiceRenderer());
		}
		
		recalculateTotals();
	}

	
	public void onClick$btnNewRecord(){
		
		if (tbRecnum.getValue()==null || tbRecnum.getValue().isEmpty()){
			return;
		}
		
		if (Messagebox.show("Procedure will create new invoice in front of order:"+bbEnqNumber.getValue()+" do you want to do that?",
				"NFYS", Messagebox.YES | Messagebox.NO,
				Messagebox.QUESTION) != Messagebox.YES){
			return;
		}
		
		
		if (valoreOpzioneMenu==1){ // customer invoice
			Custinvoice ci = (Custinvoice)listaInvoices.get((invoiceAttuale-1));
			Custinvoice ci2 = new Custinvoice();
			ci2.setCustid(ci.getCustid());
			ci2.setCustname(ci.getCustname());
			ci2.setOrder(ci.getOrder());
			ci2.setCreditterms(ci.getCreditterms());
			ci2.setCurr(ci.getCurr());
			ci2.setStat("HI");
			ci2.setType("X");
			ci2.setDeliverydt(ci.getDeliverydt());
			ci2.setCustnuminvoice(0);
			ci2.setVatyesno(false);
			ci2.setTotalvat(0);
			ci2.setTotaltaxedvat(0);
			ci2.setPorttoref(ci.getPorttoref());
			ci2.setPortid(ci.getPortid());
			ci2.setExchangerate(0);
			ci2.setPaidamount(0);
			ci2.setDeleted(false);
			ci2.setDtUp( General.date2SqlTimestamp(new Date()));
			ci2.setFuel(ci.getFuel());
			new CustinvoiceController().add(ci2);
			
		} else if (valoreOpzioneMenu==5){ // supplier invoice
			
			Suppinvoice si = (Suppinvoice)listaInvoices.get((invoiceAttuale-1));
			Suppinvoice si2 = new Suppinvoice();
			si2.setCustid(si.getCustid());
			si2.setCustname(si.getCustname());
			si2.setOrder(si.getOrder());
			si2.setCreditterms(si.getCreditterms());
			si2.setCurr(si.getCurr());
			si2.setStat("HI");
			si2.setType("X");
			si2.setDeliverydt(si.getDeliverydt());
			si2.setSuppnuminvoice("");
			si2.setVatyesno(false);
			si2.setTotvat(0);
			si2.setTottaxed(0);
			si2.setPorttoref(si.getPorttoref());
			si2.setPortidpass(si.getPortidpass());
			si2.setExchangerate(0);
			si2.setPaidamount(0);
			si2.setDeleted(false);
			si2.setDtUp( General.date2SqlTimestamp(new Date()));
			new SuppinvoiceController().add(si2);
			
		}
		
		// select new record
		changeORokEnqNumber(null);
		viewInvoiceHeader(listaInvoices.size()); // last record

	}
	
	
	public void onClick$btnCash(){
		
		if (tbRecnum.getValue()==null || tbRecnum.getValue().isEmpty()){
			return;
		}

		
		Custinvoice ci2 = new Custinvoice();
		Suppinvoice si2 = new Suppinvoice();
		
		String status = null;
		
		if (valoreOpzioneMenu==1){ // customer invoice
			Custinvoice ci = (Custinvoice)listaInvoices.get((invoiceAttuale-1));
			status = ci.getStat(); 
			ci2 = ci;

		} else if (valoreOpzioneMenu==5){ // supplier invoice
			Suppinvoice si = (Suppinvoice)listaInvoices.get((invoiceAttuale-1));
			status = si.getStat();
			si2 = si;
		}
		
		if ( !(status.equalsIgnoreCase("IV") || status.equalsIgnoreCase("CL") || status.equalsIgnoreCase("PD")) ){
			General.showNotify("Invoice status is "+status+" (Status valid for payment are: CL, IV, PD)", null, 6000, "warning");
			return; 
		}
		
		
		HashMap map = new HashMap(); 
		map.put("lNuovo", true);
			
		String docType = "";
		String ref = "";
		String invref = "";
		Integer idInvoiceRecNum = 0;
				
		if (valoreOpzioneMenu==1){ // customer invoice
			docType = "A";
			ref = ""+ci2.getOrder();
			invref = ""+ci2.getCustnuminvoice();
			idInvoiceRecNum = ci2.getRecnum();
			if (tbType.getValue().equalsIgnoreCase("C") || tbType.getValue().equalsIgnoreCase("D") ){
				docType = "C";		
			}
		} else if (valoreOpzioneMenu==5){ // supplier invoice
			docType = "P";
			ref = ""+si2.getOrder();
			invref = si2.getSuppnuminvoice();
			idInvoiceRecNum = si2.getRecnum();
			if (tbType.getValue().equalsIgnoreCase("D") ){
				docType = "D";		
			}

		}
			
		map.put("docType", docType);
		map.put("ref", ref);
		map.put("invref", invref);
		map.put("idInvoiceRecNum", idInvoiceRecNum);
		map.put("valoreOpzioneMenu", valoreOpzioneMenu);
		map.put("ci", ci2);
		map.put("si", si2);
			
		Window finestraEditCash = (Window) Executions.createComponents("/editCash.zul", null, map);
		finestraEditCash.doModal();
		

		/*
		for (int i = 0; i < boxInvoiceDetail.getItemCount(); i++) {
			Object oRiga = boxInvoiceDetail.getItemAtIndex(i).getAttribute("rigaInvoiceDetailRenderer");
			
			if (valoreOpzioneMenu==1){ 				
				Custinvoicedetail cid = (Custinvoicedetail)oRiga;
				//cid.setStat("HI");
				new CustinvoicedetailController().update(cid);
			} else if (valoreOpzioneMenu==5){
				Suppinvoicedetail sid = (Suppinvoicedetail)oRiga;
				//sid.setStat("HI");
				new SuppinvoicedetailController().update(sid);
			}
			
		}
		*/
		
		
	}
	
	
	public void onClick$btnCreditNoteDebitNote(){
		
		if (tbRecnum.getValue()==null || tbRecnum.getValue().isEmpty()){
			return;
		}
		
		if (tbType.getValue().equalsIgnoreCase("C") || tbType.getValue().equalsIgnoreCase("D") ){
			return;			
		}
		
		String creditOrDebit = "";
		if (valoreOpzioneMenu==1){ // customer invoice
			creditOrDebit = "Credit Note";
		} else if (valoreOpzioneMenu==5){ // supplier invoice
			creditOrDebit = "Debit Note";
		}
		
		if (Messagebox.show("Procedure will create a "+creditOrDebit+" in front of order:"+bbEnqNumber.getValue()+" do you want to do that?",
				"NFYS", Messagebox.YES | Messagebox.NO,
				Messagebox.QUESTION) != Messagebox.YES){
			return;
		}
		
		
		Custinvoice ci2 = new Custinvoice();
		Suppinvoice si2 = new Suppinvoice();
		
		if (valoreOpzioneMenu==1){ // customer invoice
			Custinvoice ci = (Custinvoice)listaInvoices.get((invoiceAttuale-1));
			
			ci2.setCustid(ci.getCustid());
			ci2.setCustname(ci.getCustname());
			ci2.setOrder(ci.getOrder());
			ci2.setCreditterms(ci.getCreditterms());
			ci2.setCurr(ci.getCurr());
			ci2.setStat("HI");
			ci2.setType("C");
			ci2.setDeliverydt(ci.getDeliverydt());
			ci2.setCustnuminvoice(0);
			ci2.setVatyesno(false);
			ci2.setTotalvat(0);
			ci2.setTotaltaxedvat(0);
			ci2.setPorttoref(ci.getPorttoref());
			ci2.setPortid(ci.getPortid());
			ci2.setExchangerate(0);
			ci2.setPaidamount(0);
			ci2.setDeleted(false);
			ci2.setDtUp( General.date2SqlTimestamp(new Date()));
			ci2.setInvoicedtreg(General.date2SqlTimestamp(new Date()));
			ci2.setFuel(ci.getFuel());
			ci2.setArt15(ci.getArt15());
			ci2 = new CustinvoiceController().add(ci2);			
		} else if (valoreOpzioneMenu==5){ // supplier invoice
			Suppinvoice si = (Suppinvoice)listaInvoices.get((invoiceAttuale-1));
			
			si2.setCustid(si.getCustid());
			si2.setCustname(si.getCustname());
			si2.setOrder(si.getOrder());
			si2.setCreditterms(si.getCreditterms());
			si2.setCurr(si.getCurr());
			si2.setStat("HI");
			si2.setType("D");
			si2.setDeliverydt(si.getDeliverydt());
			si2.setSuppnuminvoice("");
			si2.setVatyesno(false);
			si2.setTotvat(0);
			si2.setTottaxed(0);
			si2.setPorttoref(si.getPorttoref());
			si2.setPortidpass(si.getPortidpass());
			si2.setExchangerate(0);
			si2.setPaidamount(0);
			si2.setDeleted(false);
			si2.setDtUp( General.date2SqlTimestamp(new Date()));
			si2.setInvoicedtreg(General.date2SqlTimestamp(new Date()));
			si2.setArt15(si.getArt15());
			si2 = new SuppinvoiceController().add(si2);
		}
		
		
//		ListModelList lml = (ListModelList) boxInvoiceDetail.getListModel();

		for (int i = 0; i < boxInvoiceDetail.getItemCount(); i++) {
			Object oRiga = boxInvoiceDetail.getItemAtIndex(i).getAttribute("rigaInvoiceDetailRenderer");
			
			if (valoreOpzioneMenu==1){ 				
				Custinvoicedetail cid = (Custinvoicedetail)oRiga;
				cid.setStat("HI");
				cid.setRecnum(ci2.getRecnum());
				cid.setType("C");
				cid.setDtUp(General.date2SqlTimestamp(new Date()));
				cid.setBillitem(false);
				cid.setId(null);
				new CustinvoicedetailController().add(cid);
			} else if (valoreOpzioneMenu==5){
				Suppinvoicedetail sid = (Suppinvoicedetail)oRiga;
				sid.setStat("HI");
				sid.setRecnum(si2.getRecnum());
				sid.setType("D");
				sid.setDtUp(General.date2SqlTimestamp(new Date()));
				sid.setBillitem(false);
				sid.setIdmaster(null);
				new SuppinvoicedetailController().add(sid);
			}
			
		}
		
		// select new record
		changeORokEnqNumber(null);
		viewInvoiceHeader(listaInvoices.size()); // last record
		
		
	}
	
	
	public void onClick$btnNoteCustomer(){
		
		if (valoreOpzioneMenu==1){ // customer invoice
			
			Custinvoice ci = (Custinvoice)listaInvoices.get((invoiceAttuale-1));
			
			HashMap map = new HashMap();
			map.put("idEnqNumber", ci.getOrder());
			map.put("tbCustId", ci.getCustid() + " " + ci.getCustname());
			map.put("ibRecNum", ci.getRecnum());
			map.put("tbCustomerNote", ci.getNote());
			Sessions.getCurrent().setAttribute("TestoNota", "" );
			
			Window finestraCustomerNote = (Window) Executions.createComponents(
					"/editCustomerNoteInvoiceHeader.zul", null, map);
			finestraCustomerNote.doModal();

			String testoNota = (String)Sessions.getCurrent().getAttribute("TestoNota");
			if (testoNota!=null){
				if (!testoNota.equalsIgnoreCase(ci.getNote())){
					ci.setNote(testoNota);
					new CustinvoiceController().update(ci);
					General.showNotify("Customer's Note updated..", null, 2000);
				}
			}			
			Sessions.getCurrent().setAttribute("TestoNota", null );
			
		}
		
	}
	
	public void onCreate$windowEditCustomerNoteInvoiceHeader(Event event) {
		
		CreateEvent ce = (CreateEvent) ((ForwardEvent) event).getOrigin();
		args = (Map<String, Object>) ce.getArg();
		
		idEnqNumber.setValue((Integer)args.get("idEnqNumber"));
		tbCustId.setValue((String)args.get("tbCustId"));
		ibRecNum.setValue((Integer)args.get("ibRecNum"));
		tbCustomerNote.setValue((String)args.get("tbCustomerNote"));
		Integer sequence = (Integer)args.get("ibSeq");
		if (sequence!=null && sequence!=0){
			lblSeq.setVisible(true);
			ibSeq.setVisible(true);
			ibSeq.setValue(sequence);
			windowEditCustomerNoteInvoiceHeader.setTitle("Customer's Note: Detail");
		}

	
	}
	
	public void onClose$windowEditCustomerNoteInvoiceHeader(Event event) {
		Sessions.getCurrent().setAttribute("TestoNota", tbCustomerNote.getValue() );
	}
	
	
	public void onClick$btnCloseInvoice(){
		
		if (Messagebox.show("Have you executed \"Congruence\" operation? Do you like to proceed anyway?",
				"NFYS", Messagebox.YES | Messagebox.NO,
				Messagebox.QUESTION) != Messagebox.YES){
			return;
		}
		
		if (boxInvoiceDetail.getItemCount()==0){
			General.showNotify("No records in detail!Procedure will terminate!", null, 4000);
			return;
		}
		
		if (!tbStat.getValue().equalsIgnoreCase("HI")){
			General.showNotify("Status has been already set to " + tbStat.getValue() + "! Any other operation is unabled!", null, 4000);
			return;
		}
		
		String typeInvoice = "";
		if (valoreOpzioneMenu==1){
			typeInvoice="customer's invoice";
		} else if (valoreOpzioneMenu==5){
			typeInvoice="supplier's invoice";
		}
		
		if (Messagebox.show("Do you want really close this "+typeInvoice+"?\n This procedure will edit besides relative records in brogliaccio",
				"NFYS", Messagebox.YES | Messagebox.NO,
				Messagebox.QUESTION) != Messagebox.YES){
			return;
		}

		String testoFieldMandatory = "";
		if (valoreOpzioneMenu==1){
			if (tbCustNumInvoice.getValue()==null || tbCustNumInvoice.getValue().isEmpty() || tbCustNumInvoice.getValue().equalsIgnoreCase("null") || tbCustNumInvoice.getValue().equalsIgnoreCase("0") ){
				testoFieldMandatory += "-Invoice Number-\n";
			}
		} else if (valoreOpzioneMenu==5){
			if (tbSuppNumInvoice.getValue()==null || tbSuppNumInvoice.getValue().isEmpty() || tbSuppNumInvoice.getValue().equalsIgnoreCase("null") ){
				testoFieldMandatory += "-Invoice Number-\n";
			}
			
		}
		if (dbInvoiceDt.getValue()==null ){
			testoFieldMandatory += "-Invoice Date-\n";
		}
		if (dbDueDate.getValue()==null){
			testoFieldMandatory += "-Due Date-\n";
		}
		if (dbInvCeDtReg.getValue()==null){
			//testoFieldMandatory += "-Invoice Reg. Date-";
			dbInvCeDtReg.setValue(new Date());
		}
		
		if (!testoFieldMandatory.isEmpty()){
			testoFieldMandatory = "You can't perform the operation, before fill mandatory field: \n"+testoFieldMandatory;
			General.showNotify(testoFieldMandatory, null, 8000);
			return;
		}
		

		ListModelList lml = (ListModelList) boxInvoiceDetail.getListModel();
		boolean allRows = true;
		int quanteBilled = 0;
		for (int i = 0; i < boxInvoiceDetail.getItemCount(); i++) {
			Object oRiga = boxInvoiceDetail.getItemAtIndex(i).getAttribute("rigaInvoiceDetailRenderer");
			
			if (valoreOpzioneMenu==1){ 				
				Custinvoicedetail cid = (Custinvoicedetail)oRiga;
				if (cid.getBillitem()!=null && cid.getBillitem()){
					cid.setStat("CL");
					quanteBilled++;
					new CustinvoicedetailController().update(cid);
					if (lml.indexOf(cid) == -1) {
						lml.add(cid);
					} else {
						lml.set(lml.indexOf(cid), cid);
					}
				} else {
					allRows = false;
				}
			} else if (valoreOpzioneMenu==5){
				Suppinvoicedetail sid = (Suppinvoicedetail)oRiga;
				if (sid.getBillitem()!=null && sid.getBillitem()){
					sid.setStat("CL");
					quanteBilled++;
					new SuppinvoicedetailController().update(sid);
					if (lml.indexOf(sid) == -1) {
						lml.add(sid);
					} else {
						lml.set(lml.indexOf(sid), sid);
					}
				} else {
					allRows = false;
				}
				
			}
			
		}
		
			
		if (valoreOpzioneMenu==1){
			Custinvoice ci = (Custinvoice)listaInvoices.get((invoiceAttuale-1));
			ci.setInvoicedtreg( General.date2SqlTimestamp( dbInvCeDtReg.getValue() ) );
			new CustinvoiceController().update(ci);
		} else if (valoreOpzioneMenu==5){
			Suppinvoice si = (Suppinvoice)listaInvoices.get((invoiceAttuale-1));
			si.setInvoicedtreg( General.date2SqlTimestamp( dbInvCeDtReg.getValue() ) );
			new SuppinvoiceController().update(si);
		}			
		
		recalculateTotals();
		
		// change status in master if all detail records are to the same status
		
		// 28/4/2015, basta una riga Billed per chiudere la fattura.
		if (quanteBilled > 0 ){ // 28/4/2015 Modificato perché nel pico vecchio la fattura viene chiusa comunque.			
			tbStat.setValue("CL");
			if (valoreOpzioneMenu==1){
				Custinvoice ci = (Custinvoice)listaInvoices.get((invoiceAttuale-1));
				//Custinvoice ci = new CustinvoiceController().getxId(Integer.valueOf(tbRecnum.getValue() ));
				ci.setStat("CL");
				new CustinvoiceController().update(ci);
			} else if (valoreOpzioneMenu==5){
				Suppinvoice si = (Suppinvoice)listaInvoices.get((invoiceAttuale-1));
				si.setStat("CL");
				new SuppinvoiceController().update(si);
			}
			
			btnLockedForms.setLabel("Locked Forms");
			btnLockedForms.setStyle("color: red");
			lockedForms = true;
			
			boxInvoiceDetail.invalidate();
			controlLockedFields();
			
		} else {
			//new General().MsgBox("There is/are record/s you can't close because BillItem check is FALSE", "NFYS");
			new General().MsgBox("There is no records billed!!", "NFYS");
		}
		
	}
	
	
	public void onClick$btnGetInvoiceNumber(){
		
		if (tbCustNumInvoice.getValue()!=null && !tbCustNumInvoice.getValue().equalsIgnoreCase("null") && !tbCustNumInvoice.getValue().equalsIgnoreCase("0") && !tbCustNumInvoice.getValue().isEmpty() ){
			General.showNotify("Warning! This invoice number has been already assigned", null, 8000);
			return;
		}
		
		if (Messagebox.show("Warning you must get Invoice Number only when you are sure to process invoice! Do you want to proceed?",
				"NFYS", Messagebox.YES | Messagebox.NO,
				Messagebox.QUESTION) != Messagebox.YES){ 
			return;
		}

		boolean billItem = false;
		for (int i = 0; i < boxInvoiceDetail.getItemCount(); i++) {
			Object oRiga = boxInvoiceDetail.getItemAtIndex(i).getAttribute("rigaInvoiceDetailRenderer");
			
			if (valoreOpzioneMenu==1){ // sarà sempre 1				
				Custinvoicedetail cid = (Custinvoicedetail)oRiga;
				if (cid.getBillitem()!=null && cid.getBillitem()){
					billItem = true;
					break;
				}				
			}
			
		}
		
		if(!billItem){
			General.showNotify("You can't obtain any invoice number: there is/are no detailed record set to BILL", null, 6000);
			return;
		}

		if (dbInvoiceDt.getValue()==null ){
			General.showNotify("You can't assign invoice number to an invoice without invoice date!", null, 6000);
			return;
		}

		Integer lastId = new InvoicecounterController().lastId();
		Invoicecounter ic = new Invoicecounter();
		Integer lastNumber = 0;
		if (lastId!=null){
			Invoicecounter ic2 = new InvoicecounterController().getxId(lastId);
			lastNumber = ic2.getInvnumb();
		}
		ic.setInvnumb(lastNumber+1);
		ic.setKey(0);
		ic.setDtinv( General.date2SqlTimestamp( dbInvoiceDt.getValue() ) );
		ic = new InvoicecounterController().add(ic);
		tbCustNumInvoice.setValue(""+ic.getInvnumb());
		
		Custinvoice ci = (Custinvoice)listaInvoices.get((invoiceAttuale-1));
		//Custinvoice ci = new CustinvoiceController().getxId(Integer.valueOf(tbRecnum.getValue() ));
		ci.setCustnuminvoice( Integer.valueOf( tbCustNumInvoice.getValue() ) );
		ci.setInvoicedt( General.date2SqlTimestamp( dbInvoiceDt.getValue() ) );
		new CustinvoiceController().update(ci);
		General.showNotify("Invoice number updated..", null, 2000);
		changeFullInvoiceRef();
		
	}
	
	
	public void onFocus$tbCustNumInvoice(Event event){
		tbCustNumInvoice.setAttribute("valorePrecedente", ""+tbCustNumInvoice.getValue() );
	}
	
	@SuppressWarnings("deprecation")
	public void onChange$tbCustNumInvoice(Event event){
		
		String valore = tbCustNumInvoice.getValue();
		valore = (valore==null||valore.isEmpty()?"":valore);
		
		if (valore.isEmpty()){
			return;
		}
		
		String valorePrecedente = (String) tbCustNumInvoice.getAttribute("valorePrecedente");
		
			
		//InputEvent ie = (InputEvent)event;
		boolean billItem = false;
		for (int i = 0; i < boxInvoiceDetail.getItemCount(); i++) {
			Object oRiga = boxInvoiceDetail.getItemAtIndex(i).getAttribute("rigaInvoiceDetailRenderer");
			
			if (valoreOpzioneMenu==1){ // sarà sempre 1		
				Custinvoicedetail cid = (Custinvoicedetail)oRiga;
				if (cid.getBillitem()!=null && cid.getBillitem()){
					billItem = true;
					break;
				}				
			}
			
		}
		
		if(!billItem){
			General.showNotify("You can't assign any invoice number! there is/are no detailed record set to BILL", null, 6000);
			tbCustNumInvoice.setValue(valorePrecedente);
			return;
		}

		if (dbInvoiceDt.getValue()==null ){
			General.showNotify("You can't assign invoice number to an invoice without invoice date!", null, 6000);
			tbCustNumInvoice.setValue(valorePrecedente);
			return;
		}

		// Checking if invoice number already exists
		if (valoreOpzioneMenu==1){
			Integer quante = new CustinvoiceController().getCountForInvoiceNumberAndYear( Integer.valueOf(valore), dbInvoiceDt.getValue().getYear()+1900 ); 
			if (quante>0){			
				General.showNotify("You are trying to assign a customer invoice number that already exists!", null, 6000);
				tbCustNumInvoice.setValue(valorePrecedente);
				return;
			}
		}
		
		if (valoreOpzioneMenu==1 && Messagebox.show("Warning!!! You are trying to change number of the invoice under your own responsability: all detailed items will be edited!! Are you sure?",
				"NFYS", Messagebox.YES | Messagebox.NO,
				Messagebox.QUESTION) != Messagebox.YES){
			tbCustNumInvoice.setValue(valorePrecedente);
			return;
		}
		
		Invoicecounter ic = new Invoicecounter();
		ic.setInvnumb(Integer.valueOf(valore));
		ic.setKey(0);
		ic.setDtinv( General.date2SqlTimestamp( dbInvoiceDt.getValue() ) );
		ic = new InvoicecounterController().add(ic);
		
		Custinvoice ci = (Custinvoice)listaInvoices.get((invoiceAttuale-1));
		ci.setCustnuminvoice( Integer.valueOf( tbCustNumInvoice.getValue() ) );
		ci.setInvoicedt( General.date2SqlTimestamp( dbInvoiceDt.getValue() ) );
		new CustinvoiceController().update(ci);
		
		//  update invoice number on detail
		for (int i = 0; i < boxInvoiceDetail.getItemCount(); i++) {
			Object oRiga = boxInvoiceDetail.getItemAtIndex(i).getAttribute("rigaInvoiceDetailRenderer");
			if (valoreOpzioneMenu==1){ // sarà sempre 1		
				Custinvoicedetail cid = (Custinvoicedetail)oRiga;
				if (cid.getBillitem()!=null && cid.getBillitem()==true && cid.getStat().equalsIgnoreCase("HI")){
					cid.setCustnuminvoice(ci.getCustnuminvoice());
					new CustinvoicedetailController().update(cid);
				}
			}			
		}

		General.showNotify("Invoice number updated..", null, 2000);
		changeFullInvoiceRef();

	}
	
	
	public void onFocus$tbSuppNumInvoice(Event event){
		tbSuppNumInvoice.setAttribute("valorePrecedente", tbSuppNumInvoice.getValue() );
	}
	
	public void onChange$tbSuppNumInvoice(Event event){
		
		String valore = tbSuppNumInvoice.getValue();
		String valorePrecedente = (String) tbSuppNumInvoice.getAttribute("valorePrecedente");
			
		//InputEvent ie = (InputEvent)event;
		boolean billItem = false;
		for (int i = 0; i < boxInvoiceDetail.getItemCount(); i++) {
			Object oRiga = boxInvoiceDetail.getItemAtIndex(i).getAttribute("rigaInvoiceDetailRenderer");
			
			if (valoreOpzioneMenu==5){ 		
				Suppinvoicedetail sid = (Suppinvoicedetail)oRiga;
				if (sid.getBillitem() != null && sid.getBillitem()){
					billItem = true;
					break;
				}				
			}
			
		}
		
		if(!billItem){
			General.showNotify("You can't assign any invoice number! there is/are no detailed record set to BILL", null, 6000);
			tbSuppNumInvoice.setValue(valorePrecedente);
			return;
		}

		if (dbInvoiceDt.getValue()==null ){
			General.showNotify("You can't assign invoice number to an invoice without invoice date!", null, 6000);
			tbSuppNumInvoice.setValue(valorePrecedente);
			return; 
		}

		// Checking if invoice number already exists
		/*
		Integer quante = new CustinvoiceController().getCountForInvoiceNumberAndYear( Integer.valueOf(valore), dbInvoiceDt.getValue().getYear()+1900 ); 
		if (quante>0){			
			General.showNotify("You are trying to assign a customer invoice number that already exists!", null, 6000);
			tbCustNumInvoice.setValue(valorePrecedente);
			return;
		}

		
		
		if (Messagebox.show("Warning!!! You are trying to change number of the invoice under your own responsability: all detailed items will be edited!! Are you sure?",
				"NFYS", Messagebox.YES | Messagebox.NO,
				Messagebox.QUESTION) != Messagebox.YES){
			tbSuppNumInvoice.setValue(valorePrecedente);
			return;
		}
		

		Invoicecounter ic = new Invoicecounter();
		ic.setInvnumb(Integer.valueOf(valore));
		ic.setKey(0);
		ic.setDtinv( General.date2SqlTimestamp( dbInvoiceDt.getValue() ) );
		ic = new InvoicecounterController().add(ic);
		*/
		
		Suppinvoice si = (Suppinvoice)listaInvoices.get((invoiceAttuale-1));
		si.setSuppnuminvoice( tbSuppNumInvoice.getValue() );
		si.setInvoicedt( General.date2SqlTimestamp( dbInvoiceDt.getValue() ) );
		new SuppinvoiceController().update(si);
		
		//  update invoice number on detail
		for (int i = 0; i < boxInvoiceDetail.getItemCount(); i++) {
			Object oRiga = boxInvoiceDetail.getItemAtIndex(i).getAttribute("rigaInvoiceDetailRenderer");
			if (valoreOpzioneMenu==5){ 		
				Suppinvoicedetail sid = (Suppinvoicedetail)oRiga;
				
				if (sid.getBillitem()!=null && sid.getBillitem()==true && sid.getStat().equalsIgnoreCase("HI")){
					sid.setSuppnuminvoice(si.getSuppnuminvoice());
					new SuppinvoicedetailController().update(sid);
				}
			}			
		}

		General.showNotify("Invoice number updated..", null, 2000);
		changeFullInvoiceRef();

	}
	
	public void onFocus$dbInvoiceDt(){
		if (dbInvoiceDt.getValue()==null){
			dbInvoiceDt.setValue(new Date());
		}
	}
	
	public void onChange$dbInvoiceDt(){
		changeFullInvoiceRef();
	}
	
	public void onChange$dbXChRate(){
		if (valoreOpzioneMenu==1){
			Custinvoice ci = (Custinvoice)listaInvoices.get((invoiceAttuale-1));
			if (!lockedForms){
				ci.setExchangerate(dbXChRate.getValue());
				new CustinvoiceController().update(ci);
				General.showNotify("Exchange rate updated..", null, 2000);
			} else {
				dbXChRate.setValue(ci.getExchangerate());
				General.showNotify("Locked Form..", null, 2000);
			}
		} else if (valoreOpzioneMenu==5){
			Suppinvoice si = (Suppinvoice)listaInvoices.get((invoiceAttuale-1));
			if (!lockedForms){
				si.setExchangerate(dbXChRate.getValue());
				new SuppinvoiceController().update(si);
				General.showNotify("Exchange rate updated..", null, 2000);
			} else {
				tbMemento.setValue(si.getMemento());
				dbXChRate.setValue(si.getExchangerate());
				General.showNotify("Locked Form..", null, 2000);
			}
		}
			
	}
	
	public void onClick$btnMarkTheWholeInvoice(){
		
		ListModelList lml = (ListModelList) boxInvoiceDetail.getListModel();
		for (int i = 0; i < boxInvoiceDetail.getItemCount(); i++) {
			Object oRiga = boxInvoiceDetail.getItemAtIndex(i).getAttribute("rigaInvoiceDetailRenderer");
			if (valoreOpzioneMenu==1){ // sarà sempre 1		
				Custinvoicedetail cid = (Custinvoicedetail)oRiga;
				cid.setBillitem(true);
				new CustinvoicedetailController().update(cid);				
				if (lml.indexOf(cid) == -1) {
					lml.add(cid);
				} else {
					lml.set(lml.indexOf(cid), cid);
				}
			}			
		}
		General.showNotify("Each record in detail has already been billed!", null, 2000);
	}
		
	
	public void onClick$btnCongruence(){
		// congruence between active and passive invoice
		boolean exists = true;
		
		if (valoreOpzioneMenu==5){
			return;  // non si usa sembra il controllo della congruenza nelle fatture passive
		}
		
		
		Integer countActive = boxInvoiceDetail.getItemCount();
		if (countActive==0){
			General.showNotify("No record/s present in active invoice; maybe order not confirmed to customer", null, 6000);
			return;
		}

		Integer countPassive = new SuppinvoicedetailController().countInvoicesxOrderNumber( Integer.valueOf( bbEnqNumber.getValue() ) );
		if (countPassive==0){
			General.showNotify("No record/s present in passive invoice; maybe order not confirmed to supplier", null, 6000);
			return;
		}
		
		Integer countReqshipfuelassdetail = new ReqshipfuelassdetailController().countDetailxOrderNumber( Integer.valueOf(bbEnqNumber.getValue() ) );
		if (countReqshipfuelassdetail  > countActive){
			General.showNotify("Warning! There can be records in detail order not present in Invoice Record", null, 6000);
		} else if (countReqshipfuelassdetail < countActive ){
			General.showNotify("Warning! There are records in Invoice Record not present in detail order", null, 6000);
		}
		
		if (countActive != countPassive ){
			if (Messagebox.show("There is a discrepance between passive invoice/s and active invoice; \n" +
					" passive invoice has/have " + countPassive + " rows and current active invoice "+
					"has " + countActive + " rows, do you want to check for "+
					"difference?",
					"NFYS", Messagebox.YES | Messagebox.NO,
					Messagebox.QUESTION) == Messagebox.YES){
					
				// active invoice has more records than passive invoice
				if (countActive > countPassive){					
					for (int i = 0; i < boxInvoiceDetail.getItemCount(); i++) {
						Object oRiga = boxInvoiceDetail.getItemAtIndex(i).getAttribute("rigaInvoiceDetailRenderer");
						if (valoreOpzioneMenu==1){ // sarà sempre 1		
							Custinvoicedetail cid = (Custinvoicedetail)oRiga;
							Suppinvoicedetail suppinvoicedetail = new SuppinvoicedetailController().getSuppinvoicedetail(cid.getProductid()	, cid.getOrder());
							if (suppinvoicedetail==null){
								new General().MsgBox("Record: " + cid.getOrder() + "/" + " PrID: " + cid.getProductid() + " PrName: " +cid.getProductname().trim() + " not found; this record is present only in customer's invoice", "NFYS");
							}
						}			
					}
				}
				
				// active invoice has less records than passive invoice
				if (countActive > countPassive){
					List<Suppinvoicedetail> listPassive = new SuppinvoicedetailController().getList( Integer.valueOf( bbEnqNumber.getValue() ) );
					if (listPassive.size()==0){
						new General().MsgBox("Zero records", "NFYS");
					}
					for (int i = 0; i < listPassive.size(); i++) {
						Suppinvoicedetail sid = listPassive.get(i);
						Custinvoicedetail cid = new CustinvoicedetailController().getCustinvoicedetail(sid.getProductid(), sid.getOrder());
						if (cid==null){
							new General().MsgBox("Record: " + sid.getOrder() + "/" + " PrId: " + sid.getProductid() + " PrName: " + sid.getProductname().trim() + " not found; this record is present only in supplier invoice", "NFYS");
						}
					}
					
					
				}
				
				
			}
		} else { // active invoice has number of record equal to invoicepassive
				// check if records are the same
			
			// active invoice has more records than passive invoice
			if (countActive > countPassive){					
				for (int i = 0; i < boxInvoiceDetail.getItemCount(); i++) {
					Object oRiga = boxInvoiceDetail.getItemAtIndex(i).getAttribute("rigaInvoiceDetailRenderer");
					if (valoreOpzioneMenu==1){ // sarà sempre 1		
						Custinvoicedetail cid = (Custinvoicedetail)oRiga;
						Suppinvoicedetail suppinvoicedetail = new SuppinvoicedetailController().getSuppinvoicedetail(cid.getProductid()	, cid.getOrder());
						if (suppinvoicedetail==null){
							new General().MsgBox("Record: " + cid.getOrder() + "/" + " PrID: " + cid.getProductid() + " PrName: " +cid.getProductname().trim() + " not found; this record is present only in customer's invoice", "NFYS");
							exists = false;
						}
					}			
				}
			}
			
			// active invoice has less records than passive invoice
			if (countActive > countPassive){
				List<Suppinvoicedetail> listPassive = new SuppinvoicedetailController().getList( Integer.valueOf( bbEnqNumber.getValue() ) );
				if (listPassive.size()==0){
					new General().MsgBox("Zero records", "NFYS");
				}
				for (int i = 0; i < listPassive.size(); i++) {
					Suppinvoicedetail sid = listPassive.get(i);
					Custinvoicedetail cid = new CustinvoicedetailController().getCustinvoicedetail(sid.getProductid(), sid.getOrder());
					if (cid==null){
						new General().MsgBox("Record: " + sid.getOrder() + "/" + " PrId: " + sid.getProductid() + " PrName: " + sid.getProductname().trim() + " not found; this record is present only in supplier invoice", "NFYS");
						exists = false;
					}
				}
				
				
			}
			
			if (exists){
				new General().MsgBox("Congruence between active and passive invoice is OK", "NFYS");
			}
			
		}
		
		
	}
	
	
	public void onClick$btnAbout(){
		
		if (tbRecnum.getValue()==null || tbRecnum.getValue().isEmpty()){
			return;
		}
		
		Integer orderNum = Integer.valueOf( bbEnqNumber.getValue() );
		if (orderNum==null || orderNum.equals(0)){
			return;
		}
		
		Integer countActive = boxInvoiceDetail.getItemCount();
		if (countActive==0){
			General.showNotify("No record/s present in active invoice; maybe order not confirmed to customer \n Procedure will be terminate!", null, 6000);
			return;
		}

		String msg = "Current Invoice has following suppliers:\n";
				
		List<Suppinvoicedetail> suppInvoiceDetail = new SuppinvoicedetailController().getList(orderNum);
		for (Suppinvoicedetail sid : suppInvoiceDetail) {
			msg = msg + " " +sid.getSuppname().trim() + ": Sequence "+sid.getSeq()+"\n";
		}
		General.showNotify(msg, null, 10000);
		
	}
	
	private class CustInvoiceRenderer implements ListitemRenderer {

		@Override
		public void render(Listitem item, Object data, int index)
				throws Exception {

			Custinvoicedetail cid = (Custinvoicedetail)data;
			
			new Listcell(""+cid.getOrder()).setParent(item);
			new Listcell(""+cid.getSeq()).setParent(item);
			
			//new Listcell(""+cid.getProductname()).setParent(item);
			//Label lblProductName = new Label(""+General.limitaString( cid.getProductname(), 25 ) );
			
			Button btnProduct = new Button();
			btnProduct.setLabel(General.limitaString( cid.getProductname(), 35 ));
			//btnProduct.setWidth("24x");
			btnProduct.setStyle("text-align: left; padding: 1px 1px 1px;");
			
			Listcell lc = new Listcell();
			//lc.appendChild(lblProductName);
			lc.appendChild(btnProduct);
			lc.setParent(item);
			
			btnProduct.addEventListener("onClick", new EventListener() {
				public void onEvent(Event event) {
					Component componente = event.getTarget();
					
					if (lockedForms){
						return;
					}
					
					Integer iIndex = ((Listitem)componente.getParent().getParent()).getIndex();
					Object oRigaDetail = boxInvoiceDetail.getItemAtIndex(iIndex).getAttribute("rigaInvoiceDetailRenderer");
					Custinvoicedetail cid = (Custinvoicedetail)oRigaDetail;
					
					HashMap map = new HashMap();
					map.put("tastoSeleziona", "S" );
					
					Sessions.getCurrent().setAttribute("codiceProductSelezionato", null );
					
					Window finestraProducts = (Window) Executions.createComponents(
							"/products.zul", null, map);
					finestraProducts.doModal();
					
					ListModelList lml = (ListModelList) boxInvoiceDetail.getListModel();

					String idProduct = (String)Sessions.getCurrent().getAttribute("codiceProductSelezionato");
					if (idProduct!=null && !idProduct.isEmpty()){
						Product product = new ProductsController().getProductxId(Integer.valueOf(idProduct));
						
						if (!(product.getId().equals(cid.getProductid()))){
							cid.setProductid(Integer.valueOf(idProduct));
							cid.setProductname(product.getProductname());
							new CustinvoicedetailController().update(cid);
							
							if (lml.indexOf(cid) == -1) {
								lml.add(cid);
							} else {
								lml.set(lml.indexOf(cid), cid);
							}

							General.showNotify("Product updated..", null, 2000);
						}

					}			
					Sessions.getCurrent().setAttribute("codiceProductSelezionato", null );


				}
				});
			
			
			//new Listcell(""+cid.getUm()).setParent(item);
			
			//Label lblUM = new Label(""+General.limitaString( cid.getUm(), 3 ) );
			
			Button btnUM = new Button();
			btnUM.setLabel(""+cid.getUm() );
			//btnUM.setWidth("40px");
			btnUM.setStyle("text-align: left; padding: 0px 0px 0px;");
			
			lc = new Listcell();
			//lc.appendChild(lblUM);
			lc.appendChild(btnUM);
			lc.setParent(item);
			
			btnUM.addEventListener("onClick", new EventListener() {
				public void onEvent(Event event) {
					Component componente = event.getTarget();
					
					if (lockedForms){
						return;
					}
					
					Integer iIndex = ((Listitem)componente.getParent().getParent()).getIndex();
					Object oRigaDetail = boxInvoiceDetail.getItemAtIndex(iIndex).getAttribute("rigaInvoiceDetailRenderer");
					Custinvoicedetail cid = (Custinvoicedetail)oRigaDetail;
										
					HashMap map = new HashMap();
					map.put("tastoSeleziona", "S" );
					
					Sessions.getCurrent().setAttribute("codiceUnitmeasureSelezionato", null );
					
					Window finestraUM = (Window) Executions.createComponents(
							"/unitmeasure.zul", null, map);
					finestraUM.doModal();
					
					ListModelList lml = (ListModelList) boxInvoiceDetail.getListModel();

					String idUM = (String)Sessions.getCurrent().getAttribute("codiceUnitmeasureSelezionato");
					if (idUM!=null && !idUM.isEmpty()){
						Unitmeasure um = new UnitmeasureController().getUnitmeasurexId(Integer.valueOf(idUM));
						
						if (!(um.getId().equals(cid.getUm()))){
							cid.setUm(um.getUm());
							new CustinvoicedetailController().update(cid);
							
							if (lml.indexOf(cid) == -1) {
								lml.add(cid);
							} else {
								lml.set(lml.indexOf(cid), cid);
							}

							General.showNotify("Unit of Measure updated..", null, 2000);
						}

					}			
					Sessions.getCurrent().setAttribute("codiceUnitmeasureSelezionato", null );


				}
				});
			
			
						
			Doublebox dbQty = new Doublebox(cid.getQuantity());
			dbQty.setInplace(!lockedForms);
			dbQty.setFormat("###,##0.000");
			dbQty.setStyle("text-align: right");

			lc = new Listcell();
			lc.appendChild(dbQty);
			lc.setParent(item);
			
			dbQty.addEventListener("onChange", new EventListener() {
				public void onEvent(Event event) {
					Component componente = event.getTarget();

					Integer iIndex = ((Listitem)componente.getParent().getParent()).getIndex();
					Object oRigaDetail = boxInvoiceDetail.getItemAtIndex(iIndex).getAttribute("rigaInvoiceDetailRenderer");
					Custinvoicedetail cid = (Custinvoicedetail)oRigaDetail;
					Double qtyOld = cid.getQuantity();
					
					
					Double value = ((Doublebox)componente).getValue();
					
					if (value==null){
						value = 0.00;
					}
					
					if (lockedForms){
						cid.setQuantity(qtyOld);
					} else {
						cid.setQuantity(value);
					}
					
					ListModelList lml = (ListModelList) boxInvoiceDetail.getListModel();


					if (!lockedForms && !(value.equals(qtyOld))){
						Double taxable = cid.getQuantity() * cid.getUnitprice();
						Double vat = cid.getCustvatperc();
						vat = taxable * vat / 100;
						Double totsalevat = taxable + vat; 
						cid.setCusttaxed(taxable);
						cid.setCustvat(vat);
						cid.setCusttotsalevat(totsalevat);
						
						new CustinvoicedetailController().update(cid);
						General.showNotify("Quantity updated..", null, 2000);
					} else {
						General.showNotify("Locked Forms..", null, 2000);
					}
						
					if (lml.indexOf(cid) == -1) {
						lml.add(cid);
					} else {
						lml.set(lml.indexOf(cid), cid);
					}
					
					recalculateTotals();

				}
				});

			
			//new Listcell( General.decimalFormat("###,##0.0000", cid.getUnitprice() ) ).setParent(item);
			
			Doublebox dbUnitPrice = new Doublebox(cid.getUnitprice());
			dbUnitPrice.setInplace(!lockedForms);
			dbUnitPrice.setFormat("###,##0.0000");
			dbUnitPrice.setStyle("text-align: right");

			lc = new Listcell();
			lc.appendChild(dbUnitPrice);
			lc.setParent(item);
			
			dbUnitPrice.addEventListener("onChange", new EventListener() {
				public void onEvent(Event event) {
					Component componente = event.getTarget();

					Integer iIndex = ((Listitem)componente.getParent().getParent()).getIndex();
					Object oRigaDetail = boxInvoiceDetail.getItemAtIndex(iIndex).getAttribute("rigaInvoiceDetailRenderer");
					Custinvoicedetail cid = (Custinvoicedetail)oRigaDetail;
					Double unitPriceOld = cid.getUnitprice();
					
					
					Double value = ((Doublebox)componente).getValue();
					
					if (value==null){
						value = 0.00;
					}
					
					if (lockedForms){
						cid.setUnitprice(unitPriceOld);
					} else {
						cid.setUnitprice(value);
					}
					
					ListModelList lml = (ListModelList) boxInvoiceDetail.getListModel();

					if (!lockedForms && !(value.equals(unitPriceOld))){
						Double taxable = cid.getQuantity() * cid.getUnitprice();
						Double vat = cid.getCustvatperc();
						vat = taxable * vat / 100;
						Double totsalevat = taxable + vat; 
						cid.setCusttaxed(taxable);
						cid.setCustvat(vat);
						cid.setCusttotsalevat(totsalevat);
						new CustinvoicedetailController().update(cid);
						General.showNotify("Unit Price updated..", null, 2000);
					} else {
						General.showNotify("Locked Forms..", null, 2000);
					}
						
					if (lml.indexOf(cid) == -1) {
						lml.add(cid);
					} else {
						lml.set(lml.indexOf(cid), cid);
					}
					
					recalculateTotals();

				}
				});

						
			Doublebox dbCustvatperc = new Doublebox(cid.getCustvatperc());
			dbCustvatperc.setInplace(!lockedForms);
			dbCustvatperc.setFormat("##0.00");
			dbCustvatperc.setMaxlength(6);
			dbCustvatperc.setStyle("text-align: right");

			lc = new Listcell();
			lc.appendChild(dbCustvatperc);
			lc.setParent(item);
			
			dbCustvatperc.addEventListener("onChange", new EventListener() {
				public void onEvent(Event event) {
					Component componente = event.getTarget(); 

					Integer iIndex = ((Listitem)componente.getParent().getParent()).getIndex();
					Object oRigaDetail = boxInvoiceDetail.getItemAtIndex(iIndex).getAttribute("rigaInvoiceDetailRenderer");
					Custinvoicedetail cid = (Custinvoicedetail)oRigaDetail;
					Double custvatpercold = cid.getCustvatperc();
					
					Double value = ((Doublebox)componente).getValue();
					
					if (value==null){
						value = 0.00;
					}
					
					if (lockedForms){
						cid.setCustvatperc(custvatpercold);
					} else {
						cid.setCustvatperc(value);
					}
					
					ListModelList lml = (ListModelList) boxInvoiceDetail.getListModel();

					if (!lockedForms && !(value.equals(custvatpercold))){
						Double taxable = cid.getQuantity() * cid.getUnitprice();
						Double vat = cid.getCustvatperc();
						vat = taxable * vat / 100;
						Double totsalevat = taxable + vat; 
						cid.setCusttaxed(taxable);
						cid.setCustvat(vat);
						cid.setCusttotsalevat(totsalevat);
						new CustinvoicedetailController().update(cid);
						General.showNotify("Unit Price updated..", null, 2000);
					} else {
						General.showNotify("Locked Forms..", null, 2000);
					}
						
					if (lml.indexOf(cid) == -1) {
						lml.add(cid);
					} else {
						lml.set(lml.indexOf(cid), cid);
					}
					
					recalculateTotals();

				}
				});

			

			final Integer numrecord = Integer.valueOf( tbRecnum.getValue() );
			final Integer iddetail = cid.getId();
			
			Checkbox billed = new Checkbox();
			billed.setChecked(( cid.getBillitem()!=null && cid.getBillitem() ));
			
			billed.addEventListener("onCheck", new EventListener() {
				public void onEvent(Event event) {
					Component componente = event.getTarget();	
					Checkbox billed = (Checkbox)componente; 
					
					if (lockedForms){
						billed.setChecked(!billed.isChecked());
						return;
					}
					
					Integer iIndex = ((Listitem)componente.getParent().getParent()).getIndex();
					Object oRigaDetail = boxInvoiceDetail.getItemAtIndex(iIndex).getAttribute("rigaInvoiceDetailRenderer");
					Custinvoicedetail cid = (Custinvoicedetail)oRigaDetail;

					cid.setBillitem(billed.isChecked());
					
					
					if (billed.isChecked()){
						
						if (!checkBilled(numrecord, iIndex)){
							return;
						}
						
						if ( cid.getCustvat()==0.00 ){
							new General().MsgBox("VAT article could be mandatory!", "NFYS");
						}						
						
					}

					new CustinvoicedetailController().update(cid);
					General.showNotify("Record updated..", null, 2000);
					recalculateTotals();

				}
				});
			
			lc = new Listcell();
			lc.appendChild(billed);
			lc.setParent(item);
			
			new Listcell( General.decimalFormat("##0.00", cid.getCusttaxed() ) ).setParent(item);
			new Listcell( General.decimalFormat("##0.00", cid.getCustvat() ) ).setParent(item);
			new Listcell( General.decimalFormat("##0.00", cid.getCusttotsalevat() ) ).setParent(item);
			
			//new Listcell( cid.getVatarticle() ).setParent(item);
			
			//Textbox tbVatarticle = new Textbox( cid.getVatarticle() );
			//tbVatarticle.setReadonly(true);
			//tbVatarticle.setWidth("34px");
			//tbVatarticle.setTooltiptext( cid.getVatarticle() );
			
			Button btnVatArticle = new Button();
			btnVatArticle.setLabel( (cid.getVatarticle()==null||cid.getVatarticle().isEmpty()?"N.A.":cid.getVatarticle() ) );
			//btnVatArticle.setWidth("26px");
			//btnVatArticle.setStyle("text-align: center");
			//btnNote.setStyle("color: red");
			
			btnVatArticle.addEventListener("onClick", new EventListener() {
				public void onEvent(Event event) {
					Component componente = event.getTarget();
					//Custinvoicedetail cid = new CustinvoicedetailController().getxId(iddetail);
					//Custinvoice ci = new CustinvoiceController().getxId(numrecord);
					
					if (lockedForms){
						return;
					}
					
					Integer iIndex = ((Listitem)componente.getParent().getParent()).getIndex();
					Object oRigaDetail = boxInvoiceDetail.getItemAtIndex(iIndex).getAttribute("rigaInvoiceDetailRenderer");
					Custinvoicedetail cid = (Custinvoicedetail)oRigaDetail;
					
					HashMap map = new HashMap();
					map.put("tastoSeleziona", "S" );
					
					Sessions.getCurrent().setAttribute("codiceVatarticleSelezionato", null );
					
					Window finestraCustomerNote = (Window) Executions.createComponents(
							"/vatarticles.zul", null, map);
					finestraCustomerNote.doModal();
					
					ListModelList lml = (ListModelList) boxInvoiceDetail.getListModel();

					String idCodVat = (String)Sessions.getCurrent().getAttribute("codiceVatarticleSelezionato");
					if (idCodVat!=null && !idCodVat.isEmpty()){
						Vatarticle vatarticle = new VatarticleController().getVatarticlexId( Integer.valueOf(idCodVat) );
						String codVat = vatarticle.getArticleNumber();
						if (!codVat.equalsIgnoreCase(cid.getVatarticle())){
							cid.setVatarticle(codVat);
							new CustinvoicedetailController().update(cid);
							
							if (lml.indexOf(cid) == -1) {
								lml.add(cid);
							} else {
								lml.set(lml.indexOf(cid), cid);
							}

							General.showNotify("Vat Article updated..", null, 2000);
						}
					}			
					Sessions.getCurrent().setAttribute("codiceVatarticleSelezionato", null );


				}
				});
			
			
			btnVatArticle.addEventListener("onRightClick", new EventListener() {
				public void onEvent(Event event) {
					Component componente = event.getTarget();
					//Custinvoicedetail cid = new CustinvoicedetailController().getxId(iddetail);
					//Custinvoice ci = new CustinvoiceController().getxId(numrecord);
					
					if (lockedForms){
						return;
					}
					
					Integer iIndex = ((Listitem)componente.getParent().getParent()).getIndex();
					Object oRigaDetail = boxInvoiceDetail.getItemAtIndex(iIndex).getAttribute("rigaInvoiceDetailRenderer");
					Custinvoicedetail cid = (Custinvoicedetail)oRigaDetail;
					
					
					ListModelList lml = (ListModelList) boxInvoiceDetail.getListModel();

					if (Messagebox.show("Remove VAT Article?",
							"NFYS", Messagebox.YES | Messagebox.NO,
							Messagebox.QUESTION) == Messagebox.YES){
							cid.setVatarticle("");
							new CustinvoicedetailController().update(cid);
							
							if (lml.indexOf(cid) == -1) {
								lml.add(cid);
							} else {
								lml.set(lml.indexOf(cid), cid);
							}

							General.showNotify("Vat Article updated..", null, 2000);
					}			


				}
				});
			
			
			lc = new Listcell();
			//lc.appendChild(tbVatarticle);
			lc.appendChild(btnVatArticle);
			lc.setParent(item);
			
						
			new Listcell( cid.getStat()).setParent(item);
						
			Button btnNote = new Button();
			btnNote.setLabel("N");
			btnNote.setStyle("color: red");
			
			btnNote.addEventListener("onClick", new EventListener() {
				public void onEvent(Event event) {
					//Component componente = event.getTarget();

					if (lockedForms){
						return;
					}
					
					Custinvoicedetail cid = new CustinvoicedetailController().getxId(iddetail);
					Custinvoice ci = new CustinvoiceController().getxId(numrecord);
					
					HashMap map = new HashMap();
					map.put("idEnqNumber", ci.getOrder());
					map.put("tbCustId", ci.getCustid() + " " + ci.getCustname());
					map.put("ibRecNum", ci.getRecnum());
					map.put("tbCustomerNote", cid.getNote());
					map.put("ibSeq", cid.getSeq());
					Sessions.getCurrent().setAttribute("TestoNota", "" );
					
					Window finestraCustomerNote = (Window) Executions.createComponents(
							"/editCustomerNoteInvoiceHeader.zul", null, map);
					finestraCustomerNote.doModal();

					String testoNota = (String)Sessions.getCurrent().getAttribute("TestoNota");
					if (testoNota!=null){
						if (!testoNota.equalsIgnoreCase(cid.getNote())){
							cid.setNote(testoNota);
							new CustinvoicedetailController().update(cid);
							General.showNotify("Customer's Note Detail updated..", null, 2000);
						}
					}			
					Sessions.getCurrent().setAttribute("TestoNota", null );


				}
				});
			
			
			lc = new Listcell();
			lc.appendChild(btnNote);
			lc.setParent(item); 
						
			item.setAttribute("rigaInvoiceDetailRenderer", data);
			
			ComponentsCtrl.applyForward(item, "onRightClick=onRightClickDetail");
			
		}
	}

	
	public void onClick$btnRemoveRow(){
		removeRow();
	}
	
	public void onClick$btnNewRow(){
		addRow();
	}
	
	private void addRow(){
		
		if (lockedForms){
			return;
		}
		
		int iIndex = 0;
		int rows = boxInvoiceDetail.getItemCount();
		iIndex = rows - 1;
		if (iIndex < 0 ){
			return;
		}
		
		
		Object oRigaDetail = boxInvoiceDetail.getItemAtIndex(iIndex).getAttribute("rigaInvoiceDetailRenderer");
		
		if (valoreOpzioneMenu==1 ){
		
			
			Custinvoicedetail cidTmp = (Custinvoicedetail)oRigaDetail;
			
			Custinvoicedetail cid = new Custinvoicedetail();
			cid.setOrder(cidTmp.getOrder());
			cid.setSeq(cidTmp.getSeq()+1);
			cid.setQuantity(0.00);
			cid.setUnitprice(0.00);
			cid.setCustvatperc(0.00);
			cid.setBillitem(false);
			cid.setRecnum(cidTmp.getRecnum());
			cid.setCustid(cidTmp.getCustid());
			cid.setCustname(cidTmp.getCustname());
			cid.setPaid(false);
			cid.setDtUp( General.date2SqlTimestamp( new Date() ) );
			cid.setType(cidTmp.getType());
			cid.setCurr(cidTmp.getCurr());
			cid.setStat("HI");
			
			ListModelList lml = (ListModelList) boxInvoiceDetail.getListModel();
	
			if (Messagebox.show("You are inserting a new record that isn't present on RequestQuote, this means that the record will be present only on active invoice, do you want to do this?",
					"NFYS", Messagebox.YES | Messagebox.NO,
					Messagebox.QUESTION) == Messagebox.YES){
				
					new CustinvoicedetailController().add(cid);				
					lml.add(cid);
	
					General.showNotify("New ROW inserted...", null, 2000);
			}
			
		} else if (valoreOpzioneMenu==5){
			
			
			Suppinvoicedetail cidTmp = (Suppinvoicedetail)oRigaDetail;
			
			Suppinvoicedetail sid = new Suppinvoicedetail();
			sid.setOrder(cidTmp.getOrder());
			sid.setSeq(cidTmp.getSeq()+1);
			sid.setQuantity(0.00);
			sid.setUnitprice(0.00);
			sid.setSuppvatperc(0.00);
			sid.setBillitem(false);
			sid.setRecnum(cidTmp.getRecnum());
			sid.setCustid(cidTmp.getCustid());
			sid.setCustname(cidTmp.getCustname());
			sid.setPaid(false);
			sid.setDtUp( General.date2SqlTimestamp( new Date() ) );
			sid.setType(cidTmp.getType());
			sid.setCurr(cidTmp.getCurr());
			sid.setStat("HI");
			
			ListModelList lml = (ListModelList) boxInvoiceDetail.getListModel();
	
			if (Messagebox.show("You are inserting a new record that isn't present on RequestQuote, this means that the record will be present only on passive invoice, do you want to do this?",
					"NFYS", Messagebox.YES | Messagebox.NO,
					Messagebox.QUESTION) == Messagebox.YES){
				
					new SuppinvoicedetailController().add(sid);				
					lml.add(sid);
	
					General.showNotify("New ROW inserted...", null, 2000);
			}

		}
		
	}
	
	private void removeRow(){
		int iIndex = boxInvoiceDetail.getSelectedIndex();
		if (iIndex == -1){
			return;
		}
		
		if (lockedForms){
			return;
		}

		Object oRigaDetail = boxInvoiceDetail.getItemAtIndex(iIndex).getAttribute("rigaInvoiceDetailRenderer");
		
		if (valoreOpzioneMenu==1 ){
		
			Custinvoicedetail cid = (Custinvoicedetail)oRigaDetail;
			
			if (cid.getStat().equalsIgnoreCase("CL") || cid.getStat().equalsIgnoreCase("PD") || cid.getStat().equalsIgnoreCase("IV") ){
				General.showNotify("You can't delete the record, its status "+cid.getStat()+" doesn't permit it!!", null, 6000);
				return;
			}
			
			ListModelList lml = (ListModelList) boxInvoiceDetail.getListModel();
	
			if (Messagebox.show("You are deleting selected ROW, are you sure?",
					"NFYS", Messagebox.YES | Messagebox.NO,
					Messagebox.QUESTION) == Messagebox.YES){
				
					new CustinvoicedetailController().remove(cid);				
					lml.remove(iIndex);
	
					General.showNotify("Selected ROW removed..", null, 2000);
			}
			
		} else if (valoreOpzioneMenu==5 ){
			

			Suppinvoicedetail sid = (Suppinvoicedetail)oRigaDetail;
			
			if (sid.getStat().equalsIgnoreCase("CL") || sid.getStat().equalsIgnoreCase("PD") || sid.getStat().equalsIgnoreCase("IV") ){
				General.showNotify("You can't delete the record, its status "+sid.getStat()+" doesn't permit it!!", null, 6000);
				return;
			}
			
			ListModelList lml = (ListModelList) boxInvoiceDetail.getListModel();
	
			if (Messagebox.show("You are deleting selected ROW, are you sure?",
					"NFYS", Messagebox.YES | Messagebox.NO,
					Messagebox.QUESTION) == Messagebox.YES){

					new SuppinvoicedetailController().remove(sid);
					lml.remove(iIndex);
	
					General.showNotify("Selected ROW removed..", null, 2000);
			}

			
		}

	}
	
	
	private boolean checkBilled(Integer numrecord, Integer iIndex){
		boolean ok = true;
		
		
		// TODO controllare nel caso sia una fattura passiva
		
		if (valoreOpzioneMenu==1){ 
		
			ListModelList lml = (ListModelList) boxInvoiceDetail.getListModel();
			//Custinvoice ci = new CustinvoiceController().getxId(numrecord);
			Custinvoice ci = (Custinvoice)listaInvoices.get((invoiceAttuale-1));
			Object oRigaDetail = boxInvoiceDetail.getItemAtIndex(iIndex).getAttribute("rigaInvoiceDetailRenderer");
			Custinvoicedetail cid = (Custinvoicedetail)oRigaDetail;
			String currencyGlobal = bbCurrency.getValue();
			boolean art15 = ci.getArt15();
			
			if (!currencyGlobal.equalsIgnoreCase(cid.getCurr())){
				new General().MsgBox("MasterCurrency is " + currencyGlobal + " and detail currency is " + cid.getCurr() + ",there is a discrepance!", "NFYS");
				ok = false;
				return ok;
			}
			
			if (!cid.getStat().equalsIgnoreCase("HI")){
				new General().MsgBox("Detail status: ["+cid.getStat()+"] doesn't permit any operation!!!", "NFYS");
				ok = false;
				return ok;			
			}
			
			if (art15){
				cid.setVatarticle("A15");
			}
			
			// looks in suppinvoice detail to check if the current record is present in art 15
			//suppinvoice = new SuppinvoiceController().get(numOrder, idSupplier);
			Suppinvoicedetail sid = new SuppinvoicedetailController().getSuppinvoicedetail(cid.getProductid(), cid.getOrder());
			if (sid==null || (sid!=null && sid.getVatarticle()==null)){
				new General().MsgBox("No corrispondence with Passive invoice Vat Article!", "NFYS");
			} else if (sid!=null){
				if (sid.getVatarticle().equalsIgnoreCase("A15") && !cid.getVatarticle().equalsIgnoreCase("A15")){
					cid.setVatarticle("A15");
					new General().MsgBox("Related item in Passive Invoice has Art15, system will put automatically A15 in VAtArticle, check for congruence", "NFYS");
				}
			}
			
			if (cid.getVatarticle()!=null && cid.getVatarticle().equalsIgnoreCase("A15")){
				cid.setCustvatperc(0);
				cid.setCustvat(0);
				cid.setCusttotsalevat(cid.getUnitprice() * cid.getQuantity());
			}
			
			if (cid.getQuantity()==0 || cid.getUnitprice() == 0){
				new General().MsgBox("You can't bill item with quantity = 0 or UnitPrice=0", "NFYS");
				ok = false;
				return ok;
			}
			
			if (cid.getTotalamount() == 0){
				new General().MsgBox("Warning!This record is not OK, redigit Quantity or UnitPrice or VAT% to recalculate", "NFYS");
				ok = false;
				return ok;			
			}
			
			
			
			cid.setBillitem(true);
			
			new CustinvoicedetailController().update(cid);
			
			if (lml.indexOf(cid) == -1) {
				//lml.add(cid);
			} else {
				lml.set(lml.indexOf(cid), cid);
			}
		} else if (valoreOpzioneMenu==5){

			ListModelList lml = (ListModelList) boxInvoiceDetail.getListModel();
			//Suppinvoice si = new SuppinvoiceController().getxId(numrecord);
			Suppinvoice si = (Suppinvoice)listaInvoices.get((invoiceAttuale-1));
			Object oRigaDetail = boxInvoiceDetail.getItemAtIndex(iIndex).getAttribute("rigaInvoiceDetailRenderer");
			Suppinvoicedetail sid = (Suppinvoicedetail)oRigaDetail;
			String currencyGlobal = bbCurrency.getValue();
			boolean art15 = (si.getArt15()!=null?si.getArt15():false);
			
			if (!currencyGlobal.equalsIgnoreCase(sid.getCurr())){
				new General().MsgBox("MasterCurrency is " + currencyGlobal + " and detail currency is " + sid.getCurr() + ",there is a discrepance!", "NFYS");
				ok = false;
				return ok;
			}
			
			if (!sid.getStat().equalsIgnoreCase("HI")){
				new General().MsgBox("Detail status: ["+sid.getStat()+"] doesn't permit any operation!!!", "NFYS");
				ok = false;
				return ok;			
			}
			
			if (art15){
				sid.setVatarticle("A15");
			}
			
			
			if (sid.getVatarticle()!=null && sid.getVatarticle().equalsIgnoreCase("A15")){
				sid.setSuppvatperc(0);
				sid.setSuppvat(0);
				sid.setTotalamount(sid.getUnitprice() * sid.getQuantity());
			}
			
			if (sid.getQuantity()==0 || sid.getUnitprice() == 0){
				new General().MsgBox("You can't bill item with quantity = 0 or UnitPrice=0", "NFYS");
				ok = false;
				return ok;
			}
			
			if (sid.getTotalamount() == 0){
				new General().MsgBox("Warning!This record is not OK, redigit Quantity or UnitPrice or VAT% to recalculate", "NFYS");
				ok = false;
				return ok;			
			}
			
			
			
			sid.setBillitem(true);
			
			new SuppinvoicedetailController().update(sid);
			
			if (lml.indexOf(sid) == -1) {
				//lml.add(cid);
			} else {
				lml.set(lml.indexOf(sid), sid);
			}

			
		}
				
		return ok;
	}
	
	private void recalculateTotals(){
		
		ListModelList lml = (ListModelList) boxInvoiceDetail.getListModel();

		Double totalAmount = 0.00, totalVat = 0.00, totalTaxed = 0.00;

		
		if (valoreOpzioneMenu==1 || valoreOpzioneMenu==2 || valoreOpzioneMenu==4){
		
			//Custinvoice ci = new CustinvoiceController().getxId(Integer.valueOf(tbRecnum.getValue() ));			
			Custinvoice ci = (Custinvoice)listaInvoices.get((invoiceAttuale-1));
			
			for (int i = 0; i < lml.getSize(); i++) {
				//Object oRigaDetail = boxInvoiceDetail.getItemAtIndex(i).getAttribute("rigaInvoiceDetailRenderer");
				Object oRigaDetail = lml.get(i);
				Custinvoicedetail cid = (Custinvoicedetail)oRigaDetail;
				if ( cid.getBillitem()!=null && cid.getBillitem() ){
					//if (cid.getStat().equalsIgnoreCase("HI")){
						totalAmount = totalAmount + cid.getTotalamount(); // imponibile
						totalVat = totalVat + cid.getCustvat(); // iva
						totalTaxed = totalTaxed + cid.getCusttotsalevat(); // imponibile + iva
					//}
					if (tbCustNumInvoice.getValue()!=null && !tbCustNumInvoice.getValue().equalsIgnoreCase("null")  && Integer.valueOf( tbCustNumInvoice.getValue() ) != 0){
						cid.setCustnuminvoice( Integer.valueOf( tbCustNumInvoice.getValue() ) );
						cid.setRecnum( Integer.valueOf(tbRecnum.getValue() ) );
						cid.setType( tbType.getValue() );
						new CustinvoicedetailController().update(cid);
						if (lml.indexOf(cid) != -1) {
							lml.set(lml.indexOf(cid), cid);
						}
					}
					
				} else {
					cid.setCustnuminvoice(0);
					new CustinvoicedetailController().update(cid);
					if (lml.indexOf(cid) != -1) {
						lml.set(lml.indexOf(cid), cid);
					}
				}
			}
			
			totalAmount = General.round(totalAmount, 2);
			totalVat = General.round(totalVat, 2);
			totalTaxed = General.round(totalTaxed, 2);
			
			ci.setTotalinvoice(totalAmount);
			ci.setTotalvat(totalVat);
			ci.setTotaltaxedvat( totalTaxed );
			new CustinvoiceController().update(ci);

			if (ci.getType().equalsIgnoreCase("C")){ // credit note
				ci.setTotalinvoice(ci.getTotalinvoice()*-1);
				ci.setTotalvat(ci.getTotalvat()*-1);
				ci.setTotaltaxedvat(ci.getTotaltaxedvat()*-1);
			}
			
			dbTotalTaxable.setValue(ci.getTotalinvoice());
			dbTotalVAT.setValue(ci.getTotalvat());
			dbTotalInvoice.setValue(ci.getTotaltaxedvat());
			
		} else if ( (valoreOpzioneMenu==5 || valoreOpzioneMenu==6 || valoreOpzioneMenu==8)) {
			//Suppinvoice si = new SuppinvoiceController().getxId(Integer.valueOf(tbRecnum.getValue() ));
			Suppinvoice si = (Suppinvoice)listaInvoices.get((invoiceAttuale-1));
			
			for (int i = 0; i < lml.getSize(); i++) {
				Object oRigaDetail = lml.get(i);
				Suppinvoicedetail sid = (Suppinvoicedetail)oRigaDetail;
				if (sid.getBillitem()!=null && sid.getBillitem()){
					//if (sid.getStat().equalsIgnoreCase("HI")){
						totalAmount = totalAmount + sid.getTotalamount(); // imponibile
						totalVat = totalVat + sid.getSuppvat(); // iva
						totalTaxed = totalTaxed + sid.getSupptaxed(); // imponibile + iva
					//}
					if (tbSuppNumInvoice.getValue()!=null && tbSuppNumInvoice.getValue().isEmpty()){
						sid.setSuppnuminvoice( tbSuppNumInvoice.getValue() );
						sid.setRecnum( Integer.valueOf(tbRecnum.getValue() ) );
						sid.setType( tbType.getValue() );
						new SuppinvoicedetailController().update(sid);
						if (lml.indexOf(sid) != -1) {
							lml.set(lml.indexOf(sid), sid);
						}
					}
					
				} else {
					sid.setSuppnuminvoice("");
					new SuppinvoicedetailController().update(sid); 
					if (lml.indexOf(sid) != -1) {
						lml.set(lml.indexOf(sid), sid);
					}
				}
			}
		
			totalAmount = General.round(totalAmount, 2);
			totalVat = General.round(totalVat, 2);
			totalTaxed = General.round(totalTaxed, 2);
			
			si.setTotalinvoice(totalAmount);
			si.setTotvat(totalVat);
			si.setTottaxed( totalTaxed );
			new SuppinvoiceController().update(si);

			if (si.getType().equalsIgnoreCase("D")){
				si.setTotalinvoice(si.getTotalinvoice()*-1);
				si.setTotvat(si.getTotvat()*-1);
				si.setTottaxed(si.getTottaxed()*-1);
			}
			
			dbTotalTaxable.setValue(si.getTottaxed());
			dbTotalVAT.setValue(si.getTotvat());
			dbTotalInvoice.setValue(si.getTotalinvoice());
			
		}

		lfTaxable.setLabel( General.decimalFormat("#,###,##0.00", totalAmount ) );
		lfVAT.setLabel( General.decimalFormat("#,###,##0.00", totalVat ) );
		lfTotVAT.setLabel( General.decimalFormat("#,###,##0.00", totalTaxed ) );
		
	}
	
	
	public void onClick$btnLockedForms(){
		
		
		if (bbEnqNumber.getValue()==null || bbEnqNumber.getValue().isEmpty() || tbStat.getValue()==null ){
			return;
		}
		
		if ( !tbStat.getValue().equalsIgnoreCase("HI") ){
			new General().MsgBox("You can't unlock to edit:Status is "+tbStat.getValue(), "NFYS");
			return;
		}
		
		lockedForms = !lockedForms;
		
		if (!lockedForms){
			btnLockedForms.setLabel("Unlocked Forms");
			btnLockedForms.setStyle("color: green");
		} else {
			btnLockedForms.setLabel("Locked Forms");
			btnLockedForms.setStyle("color: red");			
		}

		controlLockedFields();
		
	}
	
	
	private void controlLockedFields(){
	
		
		//if (valoreOpzioneMenu==1){
			tbCustNumInvoice.setReadonly(lockedForms);
			tbSuppNumInvoice.setReadonly(lockedForms);
			btnGetInvoiceNumber.setDisabled(lockedForms);
			dbInvoiceDt.setReadonly(lockedForms);
			dbInvoiceDt.setDisabled(lockedForms);
			dbDueDate.setReadonly(lockedForms);
			dbDueDate.setDisabled(lockedForms);
			dbDeliveryDate.setReadonly(lockedForms);
			dbDeliveryDate.setDisabled(lockedForms);
			bbCreditTerms.setReadonly(lockedForms);
			bbCreditTerms.setDisabled(lockedForms);
			cbFuel.setDisabled(lockedForms);
			btnNoteCustomer.setDisabled(lockedForms);
			//bbCurRecNum.setReadonly(lockedForms);
			//bbCurRecNum.setDisabled(lockedForms);
			btnCongruence.setDisabled(lockedForms);
			btnCloseInvoice.setDisabled(lockedForms);
			btnMarkTheWholeInvoice.setDisabled(lockedForms);
			bbCurrency.setReadonly(lockedForms);
			bbCurrency.setDisabled(lockedForms);
			tbInitial.setReadonly(lockedForms);
		//}
		
	}
	
	
	public void onChange$bbCreditTerms(){
		calcolaDueDate();
	}
	
	public void onSelect$boxCreditTerms(){
		calcolaDueDate();
	}
		
	private void calcolaDueDate(){
		
		if (bbCreditTerms.getValue().isEmpty()){
			dbDueDate.setValue(null);
			return;
		}
		
		Payment payment = new PaymentsController().getPaymentxTerms(bbCreditTerms.getValue());
		
		if (payment.getTerms()==null || payment.getTerms().isEmpty()){
			General.showNotify("Payment Term is not valid!!!", null, 3000, "error");
			dbDueDate.setValue(null);
			return;			
		}
		
		String terms = payment.getTerms();
		
		if (!terms.equalsIgnoreCase("E.O.M.")){
			Timestamp tmpTimeStamp = General.date2SqlTimestamp( dbDeliveryDate.getValue() );
			Calendar cal = Calendar.getInstance();
			cal.setTime(tmpTimeStamp);
			if (payment.getTerms()==null || payment.getTerms().isEmpty()){
				payment = new Payment();
			}
			if (payment.getId()==0){
				payment.setDd(0);
			}
			cal.add(Calendar.DAY_OF_WEEK, payment.getDd());
			tmpTimeStamp.setTime(cal.getTime().getTime());
			dbDueDate.setValue(tmpTimeStamp);
		} else {
			// E.O.M
			Timestamp tmpTimeStamp = General.date2SqlTimestamp( dbDeliveryDate.getValue() );
			Calendar cal = Calendar.getInstance();
			cal.setTime(tmpTimeStamp);
			cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH));						
			tmpTimeStamp.setTime(cal.getTime().getTime());
			dbDueDate.setValue(tmpTimeStamp);
		}
		
		
	}
	
	public void onChange$dbDueDate(){
		if (valoreOpzioneMenu==1){
			
			//Custinvoice ci = new CustinvoiceController().getxId(Integer.valueOf(tbRecnum.getValue() ));
			Custinvoice ci = (Custinvoice)listaInvoices.get((invoiceAttuale-1));
			ci.setDuedate( General.date2SqlTimestamp(dbDueDate.getValue()) );			
			new CustinvoiceController().update(ci);
		} else if ( (valoreOpzioneMenu==5 || valoreOpzioneMenu==6 || valoreOpzioneMenu==8)) {
			
			//Suppinvoice si = new SuppinvoiceController().getxId(Integer.valueOf(tbRecnum.getValue() ));
			Suppinvoice si = (Suppinvoice)listaInvoices.get((invoiceAttuale-1));
			si.setDuedate( General.date2SqlTimestamp(dbDueDate.getValue()) );
			new SuppinvoiceController().update(si);
		} 		
	}

	public void onChange$tbInitial(){
		changeFullInvoiceRef();
		
		if (tbInitial.getValue()!=null){
			if (valoreOpzioneMenu==1){
				//Custinvoice ci = new CustinvoiceController().getxId(Integer.valueOf(tbRecnum.getValue() ));
				Custinvoice ci = (Custinvoice)listaInvoices.get((invoiceAttuale-1));
				ci.setInitial(tbInitial.getValue());			
				new CustinvoiceController().update(ci);
			} else if ( (valoreOpzioneMenu==5 || valoreOpzioneMenu==6 || valoreOpzioneMenu==8)) {
				Suppinvoice si = (Suppinvoice)listaInvoices.get((invoiceAttuale-1));
				//Suppinvoice si = new SuppinvoiceController().getxId(Integer.valueOf(tbRecnum.getValue() ));
				si.setInitial(tbInitial.getValue());
				new SuppinvoiceController().update(si);
			} 
		}
		
	}
	
	@SuppressWarnings("deprecation")
	private void changeFullInvoiceRef(){
		String valore = tbInitial.getValue();
		valore =(valore==null?"":valore);
		String numInvoice = tbCustNumInvoice.getValue();
		if (valoreOpzioneMenu==5){
			numInvoice = tbSuppNumInvoice.getValue();
		}
		
		numInvoice = (numInvoice==null?"":numInvoice);
		Date dateInvoice = dbInvoiceDt.getValue();
		if (dateInvoice==null){
			return;
		}
		Integer year = (dateInvoice==null?0: (dateInvoice.getYear() ) + 1900);
		String partYear = ""+year;
		partYear = partYear.substring(2);
		String fir = numInvoice + "/" + valore + "/" + partYear;
		tbFullnvoiceRef.setValue(fir);		
	}
	
	public void onChange$tbPiva(){
		//Custinvoice ci = new CustinvoiceController().getxId(Integer.valueOf(tbRecnum.getValue() ));
		Custinvoice ci = (Custinvoice)listaInvoices.get((invoiceAttuale-1));
		ci.setPIva(tbPiva.getValue());
		new CustinvoiceController().update(ci);
	}

	public void onChange$tbCF(){
		//Custinvoice ci = new CustinvoiceController().getxId(Integer.valueOf(tbRecnum.getValue() ));
		Custinvoice ci = (Custinvoice)listaInvoices.get((invoiceAttuale-1));
		ci.setCfId(tbCF.getValue());
		new CustinvoiceController().update(ci);		
	}

	
	public void onClick$btnPrintInvoice() throws JRException, SQLException, FileNotFoundException{
		if (valoreOpzioneMenu!=1 && valoreOpzioneMenu!=2){
			return;
		}
		if (dbInvoiceDt.getValue()==null || dbDueDate.getValue()==null || tbInvCeDtReg.getValue()==null || dbInvCeDtReg.getValue()==null ){
			General.showNotify("Please set missing data!", null, 6000, "warning");
			return;
		}
		if (tbCustNumInvoice.getValue()==null || tbCustNumInvoice.getValue().isEmpty()){
			General.showNotify("Invoice number is missing!, This is only a draft of the invoice", null, 3000, "info");
		}
		
		
		ListModelList lml = (ListModelList) boxInvoiceDetail.getListModel();

		//Custinvoice ci = new CustinvoiceController().getxId(Integer.valueOf(tbRecnum.getValue() ));
		Custinvoice ci = (Custinvoice)listaInvoices.get((invoiceAttuale-1));

		
		int billed = 0;
		for (int i = 0; i < lml.getSize(); i++) {
			Object oRigaDetail = lml.get(i);
			Custinvoicedetail cid = (Custinvoicedetail)oRigaDetail;
			if (cid.getBillitem()!=null && cid.getBillitem()){
				billed++;
			}
		}
		if (billed==0){
			General.showNotify("At least one item must have BillItem set to Yes, system can't print any invoice", null, 6000, "warning");
			return;
		}
		if (billed!=lml.getSize()){
			if (Messagebox.show("There is a discrepance between records in the order and billed records,\n do you want to proceed anyway?",
					"NFYS", Messagebox.YES | Messagebox.NO,
					Messagebox.QUESTION) != Messagebox.YES){
				return;
			}
		}
		
		for (int i = 0; i < lml.getSize(); i++) {
			Object oRigaDetail = lml.get(i);
			Custinvoicedetail cid = (Custinvoicedetail)oRigaDetail;
			//reqshipfuelassdetail
			Reqshipfuelassdetail rsfad = new ReqshipfuelassdetailController().getReqshipfuelassdetail(cid.getOrder(), cid.getSeq());
			if (rsfad==null || rsfad.getId()==null || rsfad.getId().compareTo(0)==0){
				new General().MsgBox("Record "+cid.getOrder()+"/"+cid.getSeq()+" is not present in orders table", "NFYS");
			}
			
			if (cid.getCustnuminvoice()!=null && cid.getCustnuminvoice()!=0 && cid.getStat().equalsIgnoreCase("CL")){
				
				if (cid.getCustnuminvoice().equals(ci.getCustnuminvoice())){
					cid.setStat("IV");
					new CustinvoicedetailController().update(cid);
					if (lml.indexOf(cid) != -1) {
						lml.set(lml.indexOf(cid), cid);
					}
				}
				
			} else {
				if (cid.getStat().equalsIgnoreCase("IV")){
					new General().MsgBox("Record "+cid.getOrder()+"/"+cid.getSeq()+" : Detail status is already set to \"IV\"", "NFYS");
				} else {
					new General().MsgBox("Record "+cid.getOrder()+"/"+cid.getSeq()+" : Detail status doesn't permit update to Status \"IV\"", "NFYS");
				}
			}
		}
		
		// if all record in detail has been set to IV, set master record to IV
		boolean allRowsIV = true;
		for (int i = 0; i < lml.getSize(); i++) {
			Object oRigaDetail = lml.get(i);
			Custinvoicedetail cid = (Custinvoicedetail)oRigaDetail;
			if (!cid.getStat().equalsIgnoreCase("IV")){
				allRowsIV = false;
				break;
			}
		}
		
		if (allRowsIV){
			ci.setStat("IV");
			tbStat.setValue("IV");
			new CustinvoiceController().update(ci);
		}
		
		// Print invoice...
		
		String _utente = (String)Sessions.getCurrent().getAttribute("_utente"), _password = (String)Sessions.getCurrent().getAttribute("_password");
		
		String url = "jdbc:postgresql://localhost/pico";
		Properties props = new Properties();
		props.setProperty("user", _utente );
		props.setProperty("password", _password );
		Connection connection;
		connection = DriverManager.getConnection(url, props);

		

		// setup parameters for use with the report
		HashMap<String, Object> params = new HashMap<String,Object>();
		//params.put( "ordine", fa.getRef() );
		params.put( "PATH_IMG", new General().percorsoImg() + "/" );
		params.put("SUBREPORT_DIR", new General().percorsoFincati() + "/");
		params.put( "RecNumPar", Integer.valueOf( tbRecnum.getValue() ) );
		
		int dateFormat = cbDateFormat.getSelectedIndex();

		params.put( "PAR_DATE_FORMAT", (dateFormat<=0 ? "dd/MM/yyyy" : "MM/dd/yyyy") );
		params.put( "PAR_IMMEDIATE_INVOICE", cbImmediateInvoice.isChecked());
		
		//params.put( "PAR_DATA", data);

		// Fill the report data from the sql connection and parameters
		JasperPrint printedReport;
		String fileJasper = new General().percorsoFincati()+"/InvoiceActive.jasper";
		
		printedReport = JasperFillManager.fillReport(fileJasper, params, connection);

		String outputFilename = new General().percorsoEsporta()+"/InvoiceActive.pdf";
		
		JasperExportManager.exportReportToPdfFile( printedReport, outputFilename );

		File file = new File(outputFilename);
		Filedownload.save(file, "PDF");
		
		
	}
	
	private class EnqNumberRenderer implements ListitemRenderer {

		@Override
		public void render(Listitem item, Object data, int index)
				throws Exception {
			
			Object[] oRiga = (Object[])data;
			Integer id = (Integer)oRiga[0];
			
			Reqshipfuelass reqshipfuelass = new ReqshipfuelassController().getxId(id);
			
			Integer agentId = reqshipfuelass.getAgentid();
			String agentName = reqshipfuelass.getAgent();
			if (valoreOpzioneMenu==5){
				agentId = (Integer)oRiga[8];
				agentName = (String)oRiga[9];
			}

			Anayacht anayacht = new AnayachtController().getAnayachtxId(reqshipfuelass.getVesselnameid());

			//Port port = new PortController().getPortxId(reqshipfuelass.getIdportref());
			Timestamp deliverydt = reqshipfuelass.getDeliverydt();
			
			new Listcell(""+id).setParent(item);
			new Listcell(""+reqshipfuelass.getVesselnameid()).setParent(item);
			new Listcell(""+reqshipfuelass.getVesselname()).setParent(item);
			new Listcell(""+General.formatoFecha(deliverydt)).setParent(item);
			new Listcell(""+anayacht.getCaptain()).setParent(item);
			new Listcell(""+reqshipfuelass.getPorttoref()).setParent(item);
			new Listcell(""+anayacht.getCorporation()).setParent(item);
			new Listcell(""+reqshipfuelass.getStatus()).setParent(item);
			new Listcell(""+agentId).setParent(item);
			new Listcell(""+agentName).setParent(item);
			item.setAttribute("rigaEnqNumber", data);
		}
	}
	
	
	private class PaymentsRenderer implements ListitemRenderer {

		@Override
		public void render(Listitem item, Object data, int index)
				throws Exception {
			
			Payment payment = (Payment)data;
			new Listcell(""+payment.getTerms()).setParent(item);
			new Listcell(""+payment.getDd()).setParent(item);
			item.setAttribute("rigaPayments", data);
		}
	}

	

	

	private class SuppInvoiceRenderer implements ListitemRenderer {

		@Override
		public void render(Listitem item, Object data, int index)
				throws Exception {

			Suppinvoicedetail sid = (Suppinvoicedetail)data;

			////
			
			new Listcell(""+sid.getOrder()).setParent(item);
			new Listcell(""+sid.getSeq()).setParent(item);
					
			Button btnProduct = new Button();
			btnProduct.setLabel(General.limitaString( sid.getProductname(), 35 ));
			btnProduct.setStyle("text-align: left; padding: 1px 1px 1px;");
			
			Listcell lc = new Listcell();
			lc.appendChild(btnProduct);
			lc.setParent(item);
			
			btnProduct.addEventListener("onClick", new EventListener() {
				public void onEvent(Event event) {
					Component componente = event.getTarget();
					
					if (lockedForms){
						return;
					}
					
					Integer iIndex = ((Listitem)componente.getParent().getParent()).getIndex();
					Object oRigaDetail = boxInvoiceDetail.getItemAtIndex(iIndex).getAttribute("rigaInvoiceDetailRenderer");
					Suppinvoicedetail sid = (Suppinvoicedetail)oRigaDetail;
					
					HashMap map = new HashMap();
					map.put("tastoSeleziona", "S" );
					
					Sessions.getCurrent().setAttribute("codiceProductSelezionato", null );
					
					Window finestraProducts = (Window) Executions.createComponents(
							"/products.zul", null, map);
					finestraProducts.doModal();
					
					ListModelList lml = (ListModelList) boxInvoiceDetail.getListModel();

					String idProduct = (String)Sessions.getCurrent().getAttribute("codiceProductSelezionato");
					if (idProduct!=null && !idProduct.isEmpty()){
						Product product = new ProductsController().getProductxId(Integer.valueOf(idProduct));
						
						if (!(product.getId().equals(sid.getProductid()))){
							sid.setProductid(Integer.valueOf(idProduct));
							sid.setProductname(product.getProductname());
							new SuppinvoicedetailController().update(sid);
							
							if (lml.indexOf(sid) == -1) {
								lml.add(sid);
							} else {
								lml.set(lml.indexOf(sid), sid);
							}

							General.showNotify("Product updated..", null, 2000);
						}

					}			
					Sessions.getCurrent().setAttribute("codiceProductSelezionato", null );


				}
				});
			
			Button btnUM = new Button();
			btnUM.setLabel(""+sid.getUm());
			//btnUM.setWidth("40px");
			btnUM.setStyle("text-align: left; padding: 0px 0px 0px;");
			
			lc = new Listcell();
			lc.appendChild(btnUM);
			lc.setParent(item);
			
			btnUM.addEventListener("onClick", new EventListener() {
				public void onEvent(Event event) {
					Component componente = event.getTarget();
					
					if (lockedForms){
						return;
					}
					
					Integer iIndex = ((Listitem)componente.getParent().getParent()).getIndex();
					Object oRigaDetail = boxInvoiceDetail.getItemAtIndex(iIndex).getAttribute("rigaInvoiceDetailRenderer");
					Suppinvoicedetail sid = (Suppinvoicedetail)oRigaDetail;
										
					HashMap map = new HashMap();
					map.put("tastoSeleziona", "S" );
					
					Sessions.getCurrent().setAttribute("codiceUnitmeasureSelezionato", null );
					
					Window finestraUM = (Window) Executions.createComponents(
							"/unitmeasure.zul", null, map);
					finestraUM.doModal();
					
					ListModelList lml = (ListModelList) boxInvoiceDetail.getListModel();

					String idUM = (String)Sessions.getCurrent().getAttribute("codiceUnitmeasureSelezionato");
					if (idUM!=null && !idUM.isEmpty()){
						Unitmeasure um = new UnitmeasureController().getUnitmeasurexId(Integer.valueOf(idUM));
						
						if (!(um.getId().equals(sid.getUm()))){
							sid.setUm(um.getUm());
							new SuppinvoicedetailController().update(sid);
							
							if (lml.indexOf(sid) == -1) {
								lml.add(sid);
							} else {
								lml.set(lml.indexOf(sid), sid);
							}

							General.showNotify("Unit of Measure updated..", null, 2000);
						}

					}			
					Sessions.getCurrent().setAttribute("codiceUnitmeasureSelezionato", null );


				}
				});
			
			
						
			Doublebox dbQty = new Doublebox(sid.getQuantity());
			dbQty.setInplace(!lockedForms);
			dbQty.setFormat("###,##0.000");
			dbQty.setStyle("text-align: right");

			lc = new Listcell();
			lc.appendChild(dbQty);
			lc.setParent(item);
			
			dbQty.addEventListener("onChange", new EventListener() {
				public void onEvent(Event event) {
					Component componente = event.getTarget();

					Integer iIndex = ((Listitem)componente.getParent().getParent()).getIndex();
					Object oRigaDetail = boxInvoiceDetail.getItemAtIndex(iIndex).getAttribute("rigaInvoiceDetailRenderer");
					Suppinvoicedetail sid = (Suppinvoicedetail)oRigaDetail;
					Double qtyOld = sid.getQuantity();
					
					
					Double value = ((Doublebox)componente).getValue();
					
					if (value==null){
						value = 0.00;
					}
					
					if (lockedForms){
						sid.setQuantity(qtyOld);
					} else {
						sid.setQuantity(value);
					}
					
					ListModelList lml = (ListModelList) boxInvoiceDetail.getListModel();


					if (!lockedForms && !(value.equals(qtyOld))){
						Double taxable = sid.getQuantity() * sid.getUnitprice();
						Double vat = sid.getSuppvatperc();
						vat = taxable * vat / 100;
						Double totsalevat = taxable + vat;
						
						sid.setSupptaxed(taxable);
						sid.setSuppvat(vat);
						sid.setTotalamount(totsalevat);

						new SuppinvoicedetailController().update(sid);
						General.showNotify("Quantity updated..", null, 2000);
					} else {
						General.showNotify("Locked Forms..", null, 2000);
					}
						
					if (lml.indexOf(sid) == -1) {
						lml.add(sid);
					} else {
						lml.set(lml.indexOf(sid), sid);
					}
					
					recalculateTotals();

				}
				});

			
			//new Listcell( General.decimalFormat("###,##0.0000", cid.getUnitprice() ) ).setParent(item);
			
			Doublebox dbUnitPrice = new Doublebox(sid.getUnitprice());
			dbUnitPrice.setInplace(!lockedForms);
			dbUnitPrice.setFormat("###,##0.0000");
			dbUnitPrice.setStyle("text-align: right");

			lc = new Listcell();
			lc.appendChild(dbUnitPrice);
			lc.setParent(item);
			
			dbUnitPrice.addEventListener("onChange", new EventListener() {
				public void onEvent(Event event) {
					Component componente = event.getTarget();

					Integer iIndex = ((Listitem)componente.getParent().getParent()).getIndex();
					Object oRigaDetail = boxInvoiceDetail.getItemAtIndex(iIndex).getAttribute("rigaInvoiceDetailRenderer");
					Suppinvoicedetail sid = (Suppinvoicedetail)oRigaDetail;
					Double unitPriceOld = sid.getUnitprice();
					
					
					Double value = ((Doublebox)componente).getValue();
					
					if (value==null){
						value = 0.00;
					}
					
					if (lockedForms){
						sid.setUnitprice(unitPriceOld);
					} else {
						sid.setUnitprice(value);
					}
					
					ListModelList lml = (ListModelList) boxInvoiceDetail.getListModel();

					if (!lockedForms && !(value.equals(unitPriceOld))){
						Double taxable = sid.getQuantity() * sid.getUnitprice();
						Double vat = sid.getSuppvatperc();
						vat = taxable * vat / 100;
						Double totsalevat = taxable + vat; 
				
						sid.setSupptaxed(taxable);
						sid.setSuppvat(vat);
						sid.setTotalamount(totsalevat);
						
						new SuppinvoicedetailController().update(sid);
						
						General.showNotify("Unit Price updated..", null, 2000);
					} else {
						General.showNotify("Locked Forms..", null, 2000);
					}
						
					if (lml.indexOf(sid) == -1) {
						lml.add(sid);
					} else {
						lml.set(lml.indexOf(sid), sid);
					}
					
					recalculateTotals();

				}
				});

						
			Doublebox dbCustvatperc = new Doublebox(sid.getSuppvatperc());
			dbCustvatperc.setInplace(!lockedForms);
			dbCustvatperc.setFormat("##0.00");
			dbCustvatperc.setMaxlength(6);
			dbCustvatperc.setStyle("text-align: right");

			lc = new Listcell();
			lc.appendChild(dbCustvatperc);
			lc.setParent(item);
			
			dbCustvatperc.addEventListener("onChange", new EventListener() {
				public void onEvent(Event event) {
					Component componente = event.getTarget(); 

					Integer iIndex = ((Listitem)componente.getParent().getParent()).getIndex();
					Object oRigaDetail = boxInvoiceDetail.getItemAtIndex(iIndex).getAttribute("rigaInvoiceDetailRenderer");
					Suppinvoicedetail sid = (Suppinvoicedetail)oRigaDetail;
					Double custvatpercold = sid.getSuppvatperc();
					
					Double value = ((Doublebox)componente).getValue();
					
					if (value==null){
						value = 0.00;
					}
					
					if (lockedForms){
						sid.setSuppvatperc(custvatpercold);
					} else {
						sid.setSuppvatperc(value);
					}
					
					ListModelList lml = (ListModelList) boxInvoiceDetail.getListModel();

					if (!lockedForms && !(value.equals(custvatpercold))){
						Double taxable = sid.getQuantity() * sid.getUnitprice();
						Double vat = sid.getSuppvatperc();
						vat = taxable * vat / 100;
						Double totsalevat = taxable + vat; 
					
						sid.setSupptaxed(taxable);
						sid.setSuppvat(vat);
						sid.setTotalamount(totsalevat);

						new SuppinvoicedetailController().update(sid);
						General.showNotify("Unit Price updated..", null, 2000);
					} else {
						General.showNotify("Locked Forms..", null, 2000);
					}
						
					if (lml.indexOf(sid) == -1) {
						lml.add(sid);
					} else {
						lml.set(lml.indexOf(sid), sid);
					}
					
					recalculateTotals();

				}
				});

			

			final Integer numrecord = Integer.valueOf( tbRecnum.getValue() );
			final Integer iddetail = sid.getIdmaster();
			
			Checkbox billed = new Checkbox();
			billed.setChecked(( sid.getBillitem()!=null && sid.getBillitem() ));
			
			billed.addEventListener("onCheck", new EventListener() {
				public void onEvent(Event event) {
					Component componente = event.getTarget();	
					Checkbox billed = (Checkbox)componente; 
					
					if (lockedForms){
						billed.setChecked(!billed.isChecked());
						return;
					}
					
					Integer iIndex = ((Listitem)componente.getParent().getParent()).getIndex();
					Object oRigaDetail = boxInvoiceDetail.getItemAtIndex(iIndex).getAttribute("rigaInvoiceDetailRenderer");
					Suppinvoicedetail sid = (Suppinvoicedetail)oRigaDetail;

					sid.setBillitem(billed.isChecked());
					
					
					if (billed.isChecked()){
						
						if (!checkBilled(numrecord, iIndex)){
							return;
						}
						
						if ( sid.getSuppvat()==0.00 ){
							new General().MsgBox("VAT article could be mandatory!", "NFYS");
						}						
						
					}

					new SuppinvoicedetailController().update(sid);
					General.showNotify("Record updated..", null, 2000);
					recalculateTotals();

				}
				});
			
			lc = new Listcell();
			lc.appendChild(billed);
			lc.setParent(item);
		
			new Listcell( General.decimalFormat("##0.00", sid.getSupptaxed() ) ).setParent(item);
			new Listcell( General.decimalFormat("##0.00", sid.getSuppvat() ) ).setParent(item);
			new Listcell( General.decimalFormat("##0.00", sid.getTotalamount() ) ).setParent(item);
			
		
			Button btnVatArticle = new Button();
			btnVatArticle.setLabel( (sid.getVatarticle()==null||sid.getVatarticle().isEmpty()?"N.A.":sid.getVatarticle() ) );
			
			btnVatArticle.addEventListener("onClick", new EventListener() {
				public void onEvent(Event event) {
					Component componente = event.getTarget();
					
					if (lockedForms){
						return;
					}
					
					Integer iIndex = ((Listitem)componente.getParent().getParent()).getIndex();
					Object oRigaDetail = boxInvoiceDetail.getItemAtIndex(iIndex).getAttribute("rigaInvoiceDetailRenderer");
					Suppinvoicedetail sid = (Suppinvoicedetail)oRigaDetail;
					
					HashMap map = new HashMap();
					map.put("tastoSeleziona", "S" );
					
					Sessions.getCurrent().setAttribute("codiceVatarticleSelezionato", null );
					
					Window finestraCustomerNote = (Window) Executions.createComponents(
							"/vatarticles.zul", null, map);
					finestraCustomerNote.doModal();
					
					ListModelList lml = (ListModelList) boxInvoiceDetail.getListModel();

					String idCodVat = (String)Sessions.getCurrent().getAttribute("codiceVatarticleSelezionato");
					if (idCodVat!=null && !idCodVat.isEmpty()){
						Vatarticle vatarticle = new VatarticleController().getVatarticlexId( Integer.valueOf(idCodVat) );
						String codVat = vatarticle.getArticleNumber();
						if (!codVat.equalsIgnoreCase(sid.getVatarticle())){
							sid.setVatarticle(codVat);
							new SuppinvoicedetailController().update(sid);
							
							if (lml.indexOf(sid) == -1) {
								lml.add(sid);
							} else {
								lml.set(lml.indexOf(sid), sid);
							}

							General.showNotify("Vat Article updated..", null, 2000);
						}
					}			
					Sessions.getCurrent().setAttribute("codiceVatarticleSelezionato", null );


				}
				});
			
			
			btnVatArticle.addEventListener("onRightClick", new EventListener() {
				public void onEvent(Event event) {
					Component componente = event.getTarget();
					
					if (lockedForms){
						return;
					}
					
					Integer iIndex = ((Listitem)componente.getParent().getParent()).getIndex();
					Object oRigaDetail = boxInvoiceDetail.getItemAtIndex(iIndex).getAttribute("rigaInvoiceDetailRenderer");
					Suppinvoicedetail sid = (Suppinvoicedetail)oRigaDetail;
					
					
					ListModelList lml = (ListModelList) boxInvoiceDetail.getListModel();

					if (Messagebox.show("Remove VAT Article?",
							"NFYS", Messagebox.YES | Messagebox.NO,
							Messagebox.QUESTION) == Messagebox.YES){
							sid.setVatarticle("");
							new SuppinvoicedetailController().update(sid);
							
							if (lml.indexOf(sid) == -1) {
								lml.add(sid);
							} else {
								lml.set(lml.indexOf(sid), sid);
							}

							General.showNotify("Vat Article updated..", null, 2000);
					}			


				}
				});
			
			
			lc = new Listcell();
			//lc.appendChild(tbVatarticle);
			lc.appendChild(btnVatArticle);
			lc.setParent(item);
			
						
			new Listcell( sid.getStat()).setParent(item);
						
			/*
			Button btnNote = new Button();
			btnNote.setLabel("N");
			btnNote.setStyle("color: red");
			
			btnNote.addEventListener("onClick", new EventListener() {
				public void onEvent(Event event) {

					if (lockedForms){
						return;
					}
					
					Custinvoicedetail cid = new CustinvoicedetailController().getxId(iddetail);
					Custinvoice ci = new CustinvoiceController().getxId(numrecord);
					
					HashMap map = new HashMap();
					map.put("idEnqNumber", ci.getOrder());
					map.put("tbCustId", ci.getCustid() + " " + ci.getCustname());
					map.put("ibRecNum", ci.getRecnum());
					map.put("tbCustomerNote", cid.getNote());
					map.put("ibSeq", cid.getSeq());
					Sessions.getCurrent().setAttribute("TestoNota", "" );
					
					Window finestraCustomerNote = (Window) Executions.createComponents(
							"/editCustomerNoteInvoiceHeader.zul", null, map);
					finestraCustomerNote.doModal();

					String testoNota = (String)Sessions.getCurrent().getAttribute("TestoNota");
					if (testoNota!=null){
						if (!testoNota.equalsIgnoreCase(cid.getNote())){
							cid.setNote(testoNota);
							new CustinvoicedetailController().update(cid);
							General.showNotify("Customer's Note Detail updated..", null, 2000);
						}
					}			
					Sessions.getCurrent().setAttribute("TestoNota", null );


				}
				});
			
			
			lc = new Listcell();
			lc.appendChild(btnNote);
			lc.setParent(item); 
			*/
						
			item.setAttribute("rigaInvoiceDetailRenderer", data);
			
			ComponentsCtrl.applyForward(item, "onRightClick=onRightClickDetail");
			
			
			
			
			
		}
	}

	

	

	
	private class SupplierItemRenderer implements ComboitemRenderer {
		
		@Override
		public void render(Comboitem item, Object data, int index)
				throws Exception {
			
			Reqquote su = (Reqquote)data;
			item.setLabel(""+su.getSuppid());
			item.setDescription(su.getSupname());			
		}


	}
	
	
	private class CurrencyRenderer implements ListitemRenderer {

		@Override
		public void render(Listitem item, Object data, int index)
				throws Exception {
			
			Currency cu = (Currency)data;
			
			new Listcell(""+cu.getCurr()).setParent(item);
			new Listcell(""+cu.getCurrdesc()).setParent(item);
			item.setAttribute("rigaCurrency", data);
		}
	}

	private class AllCustInvoices implements ListitemRenderer {
		
		@Override
		public void render(Listitem item, Object data, int index)
				throws Exception {
			
			Custinvoice ci = (Custinvoice)data;
			
			new Listcell(""+(index+1)).setParent(item);
			new Listcell(""+General.formatoFecha( ci.getInvoicedt() ) ).setParent(item);
			new Listcell(""+ci.getCurr() ).setParent(item);
			new Listcell(""+General.decimalFormat( "#,###,##0.00", ci.getTotaltaxedvat() ) ).setParent(item);
			new Listcell(""+ci.getStat() ).setParent(item);
			new Listcell(""+ci.getType() ).setParent(item);
			item.setAttribute("rigaAllInvoices", data); 
		}
	}
	
	private class AllSuppInvoices implements ListitemRenderer {
		
		@Override
		public void render(Listitem item, Object data, int index)
				throws Exception {
			
			Suppinvoice si = (Suppinvoice)data;
			
			new Listcell(""+(index+1)).setParent(item);
			new Listcell(""+General.formatoFecha( si.getInvoicedt() ) ).setParent(item);
			new Listcell(""+si.getCurr() ).setParent(item);
			new Listcell(""+General.decimalFormat( "#,###,##0.00", si.getTottaxed() ) ).setParent(item);
			new Listcell(""+si.getStat() ).setParent(item);
			new Listcell(""+si.getType() ).setParent(item);
			item.setAttribute("rigaAllInvoices", data);
		}
	}
	
	

	
	
	
	private class BankItemRenderer implements ComboitemRenderer {
		
		@Override
		public void render(Comboitem item, Object data, int index)
				throws Exception {
			
			Bank bank = (Bank)data;
			item.setDescription(""+bank.getId());
			item.setLabel(""+bank.getBank());			
		}


	}

	
	public void onChange$tbMemento(){
		
		if (valoreOpzioneMenu==1){
			Custinvoice ci = (Custinvoice)listaInvoices.get((invoiceAttuale-1));
			if (!lockedForms){
				ci.setMemento(tbMemento.getValue());
				new CustinvoiceController().update(ci);
				General.showNotify("Memento updated..", null, 2000);
			} else {
				tbMemento.setValue(ci.getMemento());
				General.showNotify("Locked Form..", null, 2000);
			}
		} else if (valoreOpzioneMenu==5){
			Suppinvoice si = (Suppinvoice)listaInvoices.get((invoiceAttuale-1));
			if (!lockedForms){
				si.setMemento(tbMemento.getValue());
				new SuppinvoiceController().update(si);
				General.showNotify("Memento updated..", null, 2000);
			} else {
				tbMemento.setValue(si.getMemento());
				General.showNotify("Locked Form..", null, 2000);
			}
		}
			
	}
	
}

